最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - ng-repeat and string replace expression value - Stack Overflow

programmeradmin3浏览0评论

I am unable to find a solution to remove a substring in an angular expression while using the ng-repeat directive.

The controller is in an external javascript file, and html is as follows.

function myController($scope, $http){
  $http.get('http://localhost:3000/people.json').
    success(function(data){
      $scope.persons = data;
    });
}
<table ng-controller="myController" class="table table-striped table-hover">
  <thead class="text-center">
    <th>Name</th>
    <th>ID</th>
    <th>Address</th>
  </thead>
  <tbody>
    <tr ng-repeat="person in persons" class="text-center">
      <td>((person.name}}</td>    
      <td>{{person.id}}</td>
      <td>{{person.address}}</td>
    </tr>
  </tbody>
</table>

I am unable to find a solution to remove a substring in an angular expression while using the ng-repeat directive.

The controller is in an external javascript file, and html is as follows.

function myController($scope, $http){
  $http.get('http://localhost:3000/people.json').
    success(function(data){
      $scope.persons = data;
    });
}
<table ng-controller="myController" class="table table-striped table-hover">
  <thead class="text-center">
    <th>Name</th>
    <th>ID</th>
    <th>Address</th>
  </thead>
  <tbody>
    <tr ng-repeat="person in persons" class="text-center">
      <td>((person.name}}</td>    
      <td>{{person.id}}</td>
      <td>{{person.address}}</td>
    </tr>
  </tbody>
</table>

The localhost:3000/people.json page has a couple hundred JSON objects:

[ { name: "John Smith", id: 12345, address: "addr:789 Broadway St" },

... ]

My Question: What is the most efficient and/or easiest method of stripping out the 'addr:' substring in the address value? I don't have write access to the people.json page.

Share Improve this question asked Feb 4, 2015 at 16:50 deric4deric4 1,3368 silver badges12 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 6

add a function to your controller. something like

$scope.stripAddr = function(address) {
  return address.substring(5);
}

and change your html to

<td>{{stripAddr(person.address)}}</td>

please excuse and errors in my javascript I use coffescript all time but I hope you get the idea

Use filter that could be the best way for you. You can reuse that filter any where, where you want to remove some matching string like here we use addr:

HTML

<tr ng-repeat="person in persons" class="text-center">
  <td>((person.name}}</td>    
  <td>{{person.id}}</td>
  <td>{{person.address}}</td>
</tr>

JS

.filter('matchreplace',function() {
        return function(value, matchstring){
            return value.split(matchstring).pop()
        }
    }
  );

Working Fiddle

Thanks.

try

<td>{{person.address.substring(5)}}</td>
发布评论

评论列表(0)

  1. 暂无评论