Angularjs 将数组作为参数传递给自定义过滤器 [英] Angularjs pass an array to custom filter as parameter

查看:48
本文介绍了Angularjs 将数组作为参数传递给自定义过滤器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Angularjs 中定义自定义过滤器时,如下所示,我传入了我想要过滤的数据集和一个用作过滤器值的数组:

在数组中传递的切换按钮状态

传入过滤器的参数数组值

过滤器的调用方式:

自定义过滤器通过过滤 ng-repeat 中的数据集来检查应应用数组中的哪些值.

 .filter('filterStats', function () {返回函数(项目,paramArray){var isFilterEmpty = true;angular.forEach(paramArray, function (value, key) {如果(值 == 0){isFilterEmpty = 假;}});如果(!isFilterEmpty)//更多逻辑}}

问题: 问题是数组参数似乎无法使用自定义过滤器内部的 forEach 进行循环.参数数组显示 [Array[0]] 因此看起来是空的.任何人都可以就此事提供指导吗?可以将数组作为自定义过滤器参数传递吗?我错过了什么?

Tx.

解决方案

看起来您可能将 filters 定义为一个数组,但正在像使用对象一样使用它.

你没有在数组中放置任何索引,所以它是空的.通过执行 filters.Limited = '-1',这是向数组添加了命名属性,但数组的实际长度仍为 0.

var a = [];a.长度;//0a.something = '123';a.length//还是 0[0] = '456';a.长度;//现在 1

相反,如果您将 filters 变量定义为对象而不是数组,我想您的代码将按预期工作.

$scope.filters = {};

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.

解决方案

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 = {};

这篇关于Angularjs 将数组作为参数传递给自定义过滤器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆