[英]AngularJS, ng-repeat + filter to be called from controller
I have a tricky question 我有一个棘手的问题
html: 的HTML:
ng-repeat="item in obj.Items | filter:someFilter"
JS: JS:
$scope.someFilter = function (item) { ... }
which works. 哪个有效。 But the problem is, I need to be able to manually invoke the
someFilter
somewhere inside in controller. 但是问题是,我需要能够在控制器内部某个地方手动调用
someFilter
。
OK, I know I can do the $filter("someFilter")(...)
but that filter requires an item object
from the ng-repeat
. 好的,我知道我可以做
$filter("someFilter")(...)
但是该过滤器需要ng-repeat
的item object
。 So, how can I provide that argument ? 那么,我如何提供该论点呢?
Please find the code below for the issue raised: 请在以下代码中查找所引发的问题:
angular.forEach(obj.Items, function (key, value) {
$scope.someFilter(value);
});
You can define a filter in two ways. 您可以通过两种方式定义过滤器。
$scope
.It's your way. $scope
的函数,这是您的方式。 In the second case, when you call $filter
, then as a parameter you will need to pass an array to filter your items. 在第二种情况下,当您调用
$filter
,则需要传递一个数组来过滤您的项目作为参数。
Live example on jsfiddle jsfiddle上的实时示例
<form name="ExampleForm">
Filter by $scope function fillArr
<div ng-repeat="a in arr|filter:fillArr">
{{a}}
</div>
Filter by filter filArrFilter
<div ng-repeat="a in arr|filArrFilter">
{{a}}
</div>
Filtered in $scope manualy
<div ng-repeat="a in filteredArr">
{{a}}
</div>
</form>
And JS controller 和JS控制器
$scope.arr = [1, 2, 3, 4, 5, 6, 8];
$scope.fillArr = function(item) {
return item % 2 == 0;
}
$scope.filteredArr = $filter('filArrFilter')($scope.arr);
And JS filter 和JS过滤器
.filter('filArrFilter', function() {
return function(items) {
var result = [];
angular.forEach(items, function(item) {
if (item % 2 == 0)
result.push(item);
});
return result;
}
}) })
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.