ng-repeat - 按数据结构中的函数过滤

时间:2015-09-18 14:51:05

标签: angularjs angularjs-ng-repeat

我有一个包含json对象的数组,其中包含一个函数

items = [...{
   id:1,
   isActive: function(){
     this.id < activeId;
   }
}...];

在其他地方的指令中,我在ng-repeat中使用这个json数组。我想过滤关于该功能。

<div ng-repeat="i in items | filter:{isActive():true}"/>

然而,这不起作用。我可以用属性来做,但不能用函数调用。我怎样才能做到这一点?

2 个答案:

答案 0 :(得分:2)

您必须使用自定义过滤功能(确保来自return对象方法的isActive btw):

$scope.isActive = function(el) {
    return el.isActive();
};

并像这样使用

<div ng-repeat="i in items | filter:isActive">{{i.id}}</div>

演示: http://plnkr.co/edit/Ib8LINdHNBPDfXOBusez?p=preview

答案 1 :(得分:-1)

首先,您需要返回函数的结果:

$scope.items = [
  {
      id: 1,
      isActive: function() {
          return this.id < activeId;
      }
  },
  {/* ... */}
];

然后,在您的HTML中,只需使用orderBy过滤器。

<ul>
    <li ng-repeat="item in items|orderBy:'isActive()'">{{item.id}} - {{item.isActive()}}</li>
</ul>

这应该有效。

<强> 修改

抱歉,误解了这个问题。我不相信'filter'$过滤器会将方法作为表达式。你可能最好编写自己的过滤器。我快速刺了一下,但是只是轻轻地测试了一下,在使用它之前需要进行更彻底的测试。

/**
 * Defines a filter on the $filter provider that will call a method
 * to filter objects inside of ngRepeat.
 *
 * @return {Function}
 *    @param {Array} - the array to loop through
 *    @param {String} - the Object method name
 *    @param {Any} - the value to match against 
 *    @return {Array} - the resultant array
 */
.filter('evalMethod', [function() {
    return function(array, method, expected) {
        var results = [];
        /** 
          * loop through all items in the array
          * and bind the results to the results object
          */
        angular.forEach(array, function(item, key) {
            /** 
             * call the method against the item context,
             * if it returns as expected, push it into the results array
             */
            if (item[method].call(item) == expected) {
                this.push(item);
            }
        }, results);
        return results;
    };
}]);

然后使用标记:

<li ng-repeat="item in items|evalMethod:'isActive':true">{{item.id}} - {{item.isActive()}}</li>

然后,如果你想在控制器内(或其他任何地方)使用它,只需将$ filter作为依赖项并调用。

$filter('evalMethod')($scope.items, 'isActive', true);