[英]AngularJS Filter Hide Item If It Exists In Another Array
I have two arrays: 我有两个数组:
$scope.arr1 = [1, 2, 3];
$scope.arr2 = [2, 3, 4];
I'm trying to: 我试图:
arr1
通过arr1
ng-repeat arr1
that aren't in arr2
使用自定义过滤器仅显示arr1
中不在arr2
1
输出应为1
Here's my view: 这是我的看法:
<ul>
<li ng-repeat="item in arr1 | matcher">
{{item}}
</li>
</ul>
Here's my controller: 这是我的控制器:
var app = angular.module('plunker', []);
app.filter('matcher', function () {
for (var i = 0; i < $scope.arr1.length; i++) {
for (var j = 0; j < $scope.arr2.length; j++) {
if ($scope.arr1[i] != $scope.arr2[j]) {
return $scope.arr1[i];
}
}
}
});
app.controller('MainCtrl', function($scope) {
$scope.arr1 = [1, 2, 3];
$scope.arr2 = [2, 3, 4];
});
Here's my Plunker: http://plnkr.co/edit/Pd3QwMMNfmL62vvdD1kW?p=preview 这是我的柱塞: http ://plnkr.co/edit/Pd3QwMMNfmL62vvdD1kW?p=preview
Any idea how to get this custom filter working? 任何想法如何使这个自定义过滤器工作?
You will never get access $scope
inside the angular filter in any way, you should pass them as parameter inside your filter and then access them inside your filter function. 您永远不会以任何方式访问$scope
在角度过滤器内,您应该在过滤器内将它们作为参数传递,然后在过滤器函数内进行访问。 For making it more cleaner you could take use of .filter
& .indexOf
inside your filter. 为了使其更清洁,您可以在过滤器内部使用.filter
和.indexOf
。
HTML 的HTML
<body ng-controller="MainCtrl">
<ul>
<li ng-repeat="item in arr1 | matcher: arr2">
{{item}}
</li>
</ul>
</body>
Code 码
var app = angular.module('plunker', []);
app.filter('matcher', function() {
return function(arr1, arr2) {
return arr1.filter(function(val) {
return arr2.indexOf(val) === -1;
})
}
});
app.controller('MainCtrl', function($scope) {
$scope.arr1 = [1, 2, 3];
$scope.arr2 = [2, 3, 4];
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.