Angularjs pass an array to custom filter as parameter

前提是你 提交于 2019-12-13 02:19:36

问题


When defining a custom filter in Angularjs like below I'm passing in the data set I want filtered and an array to serve as the filter values:

Toggle buttons state passed in an array

Parameter array value passed into the filter

How the filter is called:

<div class="row" ng-repeat="item in data | filterStats:filters">

The custom filter checks which values in the array should apply by filtering the data set in ng-repeat.

   .filter('filterStats', function () {
        return function (items, paramArray) {
        var isFilterEmpty = true;
            angular.forEach(paramArray, function (value, key) {
            if (value == 0) {
                isFilterEmpty = false;
            }
        });

        if(!isFilterEmpty) 
        //More logic
   }
}

Problem: The problem is that the array parameter does not seems to be able to loop using a forEach inside of the custom filter. The parameter array shows [Array[0]] therefore seems empty. Can anyone please provide guidance on this matter? Can one pass an Array as a custom filter parameter? What am I missing?

Tx.

回答1:


Looks like you are probably defining filters as an Array but are using it like an Object.

You haven't put any indexes in the array, so it is empty. By doing filters.Limited = '-1' this is adding named properties to the array but the actual length of the array is still 0.

var a = [];
a.length; // 0
a.something = '123';
a.length // still 0
a[0] = '456';
a.length; // now 1

Instead, if you define your filters variable as an Object instead of an Array I imagine your code will work as you expect.

$scope.filters = {};



来源:https://stackoverflow.com/questions/37188106/angularjs-pass-an-array-to-custom-filter-as-parameter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!