For循环遍历自定义过滤器结果

For loop through custom filter results

我有一个应用程序列表,我有一个自定义过滤器来获取指定字段的唯一值。我 ng-repeat out checkboxes for each of these unique values to filter a table。

我需要使用唯一过滤器返回的值进行循环。这样我就可以有一个按钮取消选中 ng-repeat 中返回的所有复选框。

我让它工作,但它循环遍历所有 tables 值(数千),而不仅仅是针对唯一值。

标记:

    <div ng-repeat="cat in applications | unique : 'Category'">
       <label>
           <input name="abc" type="checkbox" ng-model="$parent.FCategory[cat.Category]" ng-value="cat" ng-init="$parent.FCategory[cat.Category]=true">{{ cat.Category }}
       </label>
    </div>

    <input type="button" ng-click="uncheckAll()">Untick

JS,唯一过滤器:

App.filter('unique', function () {
    return function (collection, keyname)
    {
        var output = [],
            keys = [];
        angular.forEach(collection, function (item) {
            var key = item[keyname];
            if (keys.indexOf(key) === -1) {
                keys.push(key);
                output.push(item);
            }
        });
        return output;
    };
});

JS,取消选中所有功能:

 $scope.uncheckAll = function () {
        for (var i = 0; i < $scope.applications.length; i++) {
            var item = $scope.applications[i].Category;
           $scope.FCategory[item] = false;

        }
    };

问题是每个记录的 'for (var i = 0; i < $scope.applications.length; i++) {' 循环,我不知道如何让“$scope.applications.length”只用于唯一的过滤结果。

我能想出的最好办法(但行不通)是...

$scope.uncheckAll = function () {
        var a = $scope.applications;

        for (var i = 0; i < $filter('unique')(a,'Category').length; i++) {
            var item = $scope.applications[i].Category;
           $scope.FCategory[item] = false;

        }
    };

解决这个问题的一种方法是将过滤后的结果存储在一个新的范围变量 (uniqueApplications) 中,然后将其传递到您的 uncheckAll 函数中:

<div ng-repeat="cat in (uniqueApplications = (applications | unique : 'Category'))">
   <label>
       <input name="abc" type="checkbox" ng-model="$parent.FCategory[cat.Category]" ng-value="cat" ng-init="$parent.FCategory[cat.Category]=true">{{ cat.Category }}
   </label>
</div>

<input type="button" ng-click="uncheckAll(uniqueApplications)">

你还需要修改你的uncheckAll函数:

$scope.uncheckAll = function (list) {
    for (var i = 0; i < list.length; i++) {
        var item = list[i].Category;
       $scope.FCategory[item] = false;

    }
};