以下是使用ng-repeat
的html的一个小例子:
<div ng-repeat="item in vm.templateList | filter: vm.myFilter">
<h3>{{item.Code}}</h3>
</div>
在Js文件中,vm.templateList
如下(作为示例):
vm.templateList = [{Code: 'a', ID: 1},
{code: 'a', ID: 2},
{code: 'b', ID: 3},
{code: 'c', ID: 4}];
想象一下,我想为ID为1的所有项目以及ID为2的项目过滤此列表。
我原来做的是这样的:
vm.filter = {ID: 1};
但这是我只能过滤1个ID上的列表。任何人都可以建议吗?
答案 0 :(得分:3)
您可以将以下AngularJS过滤器添加到您的应用程序中:
// add a custom filter to your module
angular.module('MyModule').filter('myFilter', function() {
// the filter takes an additional input filterIDs
return function(inputArray, filterIDs) {
// filter your original array to return only the objects that
// have their ID in the filterIDs array
return inputArray.filter(function (entry) {
return this.indexOf(entry.ID) !== -1;
}, filterIDs); // filterIDs here is what "this" is referencing in the line above
};
});
然后在控制器中声明过滤器数组:
vm.IDs = [1, 2];
然后你的观点应该是这样的:
<div ng-repeat="item in vm.templateList | myFilter: vm.IDs">
<h3>{{item.Code}}</h3>
</div>
答案 1 :(得分:2)
您可以使用以下内容:
HTML:
<section>
<div ng-repeat="item in vm.templateList | filter:checkFilterOptions">
<h3>{{item.Code}}</h3>
</div>
</section>
JS:
$scope.vm = {};
$scope.vm.templateList = [
{Code: 'a', ID: 1},
{Code: 'a', ID: 2},
{Code: 'b', ID: 3},
{Code: 'c', ID: 4}
];
$scope.filterOptions = [1,2,3];
$scope.checkFilterOptions = function(value, index) {
return value.ID && $scope.filterOptions.indexOf(value.ID) !== -1;
}