我使用此 Angular 过滤器来过滤掉数组中 localteam_id
属性与 $scope.whichMyteam
中保存的值匹配的对象。这工作得很好。
查看
<div ng-repeat="fixture in getFixtures | filter: {localteam_id: whichMyteam} ">
但是,我想扩展过滤器,以包含一个部分标准:因此它实际上是:
<div ng-repeat="fixture in getFixtures | filter: {localteam_id: whichMyteam && visitorteam_id: whichMyteam} ">
...但是a)这不起作用,b)即使它起作用,它也会变得有点麻烦,并且似乎证明制作自定义过滤器是合理的。
所以,我尝试制作一个。我遇到的问题是我需要引用过滤器中的 $scope.whichMyteam
值,但过滤器模块似乎无法接受/理解 $scope
。这对于过滤器在我的实例中工作至关重要,因此我不确定如何解决此问题。
到目前为止我的过滤器如下所示:
app.filter('myFixtures', function() {
return function(input) {
angular.forEach(input, function(o) {
output = [];
if (o.localteam_id === $scope.whichMyteam) {
output.push(o);
}
return output;
})
};
});
上面是一个简化版本,仅尝试匹配一个属性(这样做只是为了测试它并减少移动部件的数量)。当我在 View 中调用它时......
<div ng-repeat="fixture in getFixtures | myFixtures">
...这不起作用。控制台日志“$scope 未定义”。
更新:我尝试了这个,仍然不起作用!
过滤器
var myFilters = angular.module('myFilters', [])
myFilters.filter('myFixtures', function(whichMyteam) {
return function(input) {
angular.forEach(input, function(o) {
output = [];
if (o.localteam_id === whichMyteam) {
output.push(o);
}
return output;
})
}
});
查看
<div ng-repeat="fixture in getFixtures | myFixtures(whichMyteam)">
控制台正在记录语法错误(我认为...)
angular.js:13236 Error: [$parse:syntax]
最佳答案
让你的过滤器函数返回一个函数怎么样。
app.filter('myFixtures', function() {
return function(input, whichMyteam) {
output = [];
angular.forEach(input, function(o) {
if (o.localteam_id === whichMyteam) {
output.push(o);
}
})
return output;
};
});
然后调用传入变量的过滤函数
<div ng-repeat='fixture in getFixtures | myFixtures:whichMyteam'>
--- 示例
angular
.module('app', [])
.filter('otherFilter', otherFilter)
.controller('controller', controller);
controller.$inject = ['$scope'];
function controller($scope) {
$scope.things = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
$scope.modVal = 2;
console.log('controller');
$scope.myFilter = function(x) {
return function(y) {
return (y % x) === 0;
}
};
}
function otherFilter() {
return function(y, x) {
var out = [];
angular.forEach(y, function(val) {
if ((val % x) === 0) {
out.push(val)
}
});
return out;
}
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app='app' ng-controller='controller'>
<div ng-repeat='thing in things | filter:myFilter(modVal)'>
{{ thing }}
</div>
<br/>
<div ng-repeat='thing in things | otherFilter:modVal'>
{{ thing }}
</div>
</div>
关于arrays - 在自定义过滤器中调用 $scope ( Angular ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37577595/