如何在angularjs中基于ID过滤结果

How to filter result based on ID in angularjs?

本文关键字:ID 过滤 结果 angularjs      更新时间:2023-09-26

我想使用angularjs过滤器根据ID进行搜索。我正在生成一些基于节点ID的值,如基于userId,我正在从存储JSON对象中查找用户的名称,电话号码。

但我无法找到如何过滤结果,如果我只有ID和它的JSON对象。
我已经弄清楚了我的问题http://jsfiddle.net/U3pVM/5969/

<div ng-app ng-controller="Ctrl">
Search: <input ng-model="searchTableQuery.id">
<table id="searchTextResults" class="table table-bordered">
  <tr><th>Name</th></tr>
  <tr ng-repeat="friend in friends | filter:searchTableQuery">
    <td>{{getCurrentValue(friend.id, friends)}}</td>
  </tr>
</table>
</div>

JS

function Ctrl($scope) {
    $scope.friends = [{id: 1, name:'John', phone:'555-1276'},
                         {id: 2, name:'Mary', phone:'800-BIG-MARY'},
                         {id: 3, name:'Mike', phone:'555-4321'},
                         {id: 4, name:'Adam', phone:'555-5678'},
                         {id: 5, name:'Julie', phone:'555-8765'},
                         {id: 6, name:'Juliette', phone:'555-5678'}];
    $scope.getCurrentValue = function (id, availableData) {
        var result = _.where(availableData, { 'id': id });
        if (_.isEmpty(result)) {
            result = [{id:0,value:""}];
        };
        return result[0].name;
    }
}

如何在angularjs中使用节点ID对表进行过滤?

<div ng-app ng-controller="Ctrl">
Search: <input ng-model="searchTableQuery">
<table id="searchTextResults" class="table table-bordered">
  <tr><th>Name</th></tr>
  <tr ng-repeat="friend in friends | filter:{id:searchTableQuery}">
    <td>{{getCurrentValue(friend.id, friends)}}</td>
  </tr>
</table>
</div>

如上所述,angular确实读取了你的searchTableQuery,但不能将它识别为好友对象列表的一个属性,所以它可以过滤它,或者更清楚地说,它现在不需要将它与好友对象的哪个属性耦合。
要解决这个问题,必须强制将searchTableQuery识别为id,方法是:filter:{id:searchTableQuery} .