加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

AngularJS中ng-repeat内的动态过滤器

发布时间:2020-12-17 10:26:02 所属栏目:安全 来源:网络整理
导读:对于我的AngularJS应用程序,我在ng-repeat中有一个ng-repeat,如下所示: HTML: div ng-app="myApp" div ng-controller="myController" h2working filter/h2 div ng-repeat="category in categories" h3{{category}}/h3 div ng-repeat="item in items | filt
对于我的AngularJS应用程序,我在ng-repeat中有一个ng-repeat,如下所示:

HTML:

<div ng-app="myApp">
    <div ng-controller="myController">
        <h2>working filter</h2>
        <div ng-repeat="category in categories">
            <h3>{{category}}</h3>
            <div ng-repeat="item in items | filter:{price.red: 0} ">{{item.name}}</div>
    </div>

        <h2>broken filter</h2>
        <div ng-repeat="category in categories">
            <h3>{{category}}</h3>
            <!-- price[category] should be red,blue,yellow,depending on the category in the ng-repeat -->
            <!-- price[category] should be bigger then 0 (or not zero,negative values will not occur) -->
            <div ng-repeat="item in items | filter:{price[category]: 0} ">{{item.name}}</div>
        </div>

    </div>
</div>

使用Javascript:

var myApp = angular.module('myApp',[]);

myApp.controller('myController',function ($scope) {

    $scope.categories = ['red','blue','yellow'];
    $scope.items = [
        {name: 'one',price:{red: 0,blue: 1,yellow: 3} },{name: 'two',price:{red: 2,blue: 0,yellow: 0}},]    

});

请参阅我的jsFiddle http://jsfiddle.net/hm8qD/

所以我遇到了两个问题:

> flter不接受[]括号,因此我无法根据类别使过滤器动态化
>过滤器需要返回价格[类别]大于零的项目.

对于大于零,我可以制作自定义过滤器.但据我所知,过滤器不接受参数,所以我无法获得类别(红色,蓝色或黄色).

请注意,这是我的实际代码的简化版本,这个上下文可能没有最好的意义.我希望我能清楚地解释我需要过滤器做什么,因为我是AngularJS的新手.

显然,实际上可以将参数传递给过滤器,但是您必须创建自定义过滤器而不是使用“filter:expression”.我所做的是创建一个自定义过滤器,它将items和category作为参数,并返回带有过滤项的数组.
myApp.filter('myFilter',function () {
    return function (items,category) {
        var newItems = [];
        for (var i = 0; i < items.length; i++) {
            if (items[i].price[category] > 0) {
                newItems.push(items[i]);
            }
        };

        return newItems;
    }
});

请在此处查看更新的小提琴:http://jsfiddle.net/hm8qD/3/

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读