【问题标题】:AngularJS using a function as a filterAngularJS 使用函数作为过滤器
【发布时间】:2014-08-02 01:59:25
【问题描述】:

有一个应用,其中内容的过滤器会根据单击的按钮而变化。对于更多简单的过滤器,我已经能够弄清楚。但是现在我想创建一个过滤器来显示具有特定范围内的值的内容。

这是我正在尝试使用的功能:

$scope.isGood = function(item){
    if(!isNan(item.rating)){
        return (item.rating>49);
    }
    return alert("Something broke!!");
    //returns true if the item has a high rating (is good, 50+)
    //returns false if the item has a poor rating (is bad, 49-)
}

因为过滤器会根据点击导航的哪个部分而改变,并且导航是动态的,所以对于每个导航按钮的点击,我运行一个函数,从其link.filter 部分获取过滤器并将其放入$scope.selectedFilter,在我的ng-repeat 中使用的变量如下:

<tr class="progress" ng-repeat="idea in ideas | filter:selectedFilter">

由于我有一些过滤器,而不是注入我自己的 $filter 并需要将一堆链接在一起,我想写一些适合 $scope.selectedFilter 变量的东西,因为我只想要一个无论如何都要过滤一次。

以下是动态导航设置方式的示例:

$scope.links = [
    {'name':'About', //title that will be displayed on the link
    'URL': '#/about', //URL/view that the link will lead to/show
    'filter':'' //view may simply change so some info is hidden or revealed
    },
    {'name':'Active',
    'URL': '#/active',
    'filter': {active: true}  //these {active...} buttons are straightforward and work
    },
    {'name':'Inactive',
    'URL': '#/active',
    'filter':{active: false}
    },
    {'name':'Good Rating',
    'URL': '#/active',
    'filter': 'isGood(item.rating)' //this is the function I want to filter by when clicked
    },
    {'name':'Bad Rating',
    'URL': '#/active',
    'filter':'!isGood(item.rating)'
    }
];

这是我要过滤的内容:

$scope.ideas = [
    {'title':'Title A',
    'rating': 80,
    active: true
    },
    {'title':'Title B',
    'rating': 55, //this would have a "good rating"
    active: false
    },
    {'title':'Title C',
    'rating': 10, //this would have a "bad rating"
    active: true
    }
];

但我的过滤器无法正常工作,而且我不确定哪里出错了。我对 Angular 很陌生,我是否在某处搞砸了我的语法?我试图复制this answer 的编写方式,但没有运气。

任何帮助将不胜感激。谢谢!

【问题讨论】:

    标签: javascript angularjs filter angularjs-filter


    【解决方案1】:

    问题是过滤器值被定义为一个字符串,它需要是一个真正的函数。然后这个函数可以依次调用isGood。所以以下应该工作:

    {
       'name':'Good Rating',
       'URL': '#/active',
       'filter': function(item) {
          return $scope.isGood(item.rating);
        }
    }
    

    【讨论】:

    • 这似乎不起作用;我还尝试将实际函数内容粘贴到该函数(项目)中(而不是返回函数),但没有运气。
    • 控制台中是否出现任何错误?我注意到你写的是isNan 而不是isNaN
    • 哎呀,我猜就是这样!很惊讶它没有跳过我的 if 语句并给我警报。但是很酷,现在我知道如何在过滤器中使用函数了,谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-19
    • 1970-01-01
    • 1970-01-01
    • 2016-07-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多