有一个应用程序,其中内容的过滤器根据单击的按钮而更改。对于更直接的过滤器,我已经能够弄明白了。但现在我想创建一个过滤器,显示某个值在一定范围内的内容。
以下是我尝试使用的功能:
$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
变量的东西,因为我&# 39; d一次只能像一个过滤器一样。
以下是动态导航设置方式的示例:
$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写的方式,但没有运气。
任何帮助将不胜感激。谢谢!
答案 0 :(得分:1)
问题是过滤器值被定义为字符串,它需要是一个真正的函数。然后该函数可以依次调用isGood。所以以下内容应该有效:
{
'name':'Good Rating',
'URL': '#/active',
'filter': function(item) {
return $scope.isGood(item.rating);
}
}