过滤对象贴图而不是AngularJS中的数组

mbr*_*ort 24 javascript angularjs

给定具有$ scope属性的控制器,该属性是具有其他属性的对象而不是如下所示的数组,我应该如何过滤该ng-repeat集合?

这是一个JSFiddle:http://jsfiddle.net/ZfGx4/110/

控制器:

function HelloCntl($scope, $filter) {
    $scope.friends = {
        john: {
            name: 'John',
            phone: '555-1276'
        },
        mary: {
            name: 'Mary',
            phone: '800-BIG-MARY'
        },
        mike: {
            name: 'Mike',
            phone: '555-4321'
        },
        adam: {
            name: 'Adam',
            phone: '555-5678'
        },
        julie: {
            name: 'Julie',
            phone: '555-8765'
        }
    };
}?
Run Code Online (Sandbox Code Playgroud)

模板:

<div ng:app>
 <div ng-controller="HelloCntl">
  <input placeholder="Type to filter" ng-model="query">     
  <ul>
   <li ng-repeat="(id, friend) in friends | filter:query">
    <span>{{friend.name}} @ {{friend.phone}}</span>
   </li>
  </ul>
 </div>
</div>
Run Code Online (Sandbox Code Playgroud)

jai*_*ime 26

我会将我的数据结构更改为数组.无论如何,这是另一个过滤你的朋友对象的实现.

angular.module('filters',['utils'])
  .filter('friendFilter', function(utils){

    return function(input, query){
      if(!query) return input;
      var result = [];

      angular.forEach(input, function(friend){
        if(utils.compareStr(friend.name, query) ||
           utils.compareStr(friend.phone, query))
          result.push(friend);          
      });
      return result;
    };
  });
Run Code Online (Sandbox Code Playgroud)

这只迭代对象一次,比较by name和,phone并且可以像这样调用.

<li ng-repeat="friend in friends | friendFilter:query">
Run Code Online (Sandbox Code Playgroud)

compareStr在另一个模块中定义了,但你真的不需要这样做.

angular.module('utils', [])
  .factory('utils', function(){
    return{
      compareStr: function(stra, strb){
        stra = ("" + stra).toLowerCase();
        strb = ("" + strb).toLowerCase();
        return stra.indexOf(strb) !== -1;
      }
    };
  });
Run Code Online (Sandbox Code Playgroud)

不要忘记将filters模块注入您的应用程序

angular.module('app',['filters'])
Run Code Online (Sandbox Code Playgroud)

以下是完整的示例:http://jsbin.com/acagag/5/edit


gar*_*rst 13

我想你不能直接用'过滤器'来做.查看angular.js中的代码,这些是过滤函数的第一行:

function filterFilter() {
  return function(array, expression) {
    if (!(array instanceof Array)) return array;
Run Code Online (Sandbox Code Playgroud)

因此,如果它收到与数组不同的东西,它什么都不做.

这是一种方法,不知道我是否会推荐它,但这是一个想法:

在控制器中,只需在将数组传递给过滤器之前转换为数组:

$scope.filteredFriends = function() {
    var array = [];
    for(key in $scope.friends) {
        array.push($scope.friends[key]);
    }
    return $filter('filter')(array, $scope.query);
}
Run Code Online (Sandbox Code Playgroud)

而ng-repeat:

<li ng-repeat="friend in filteredFriends()">
Run Code Online (Sandbox Code Playgroud)

示例:http://jsbin.com/acagag/2/edit

也许更好的解决方案是编写自定义过滤器.