此问题来自this one
在Javascript中,我有这个代码来进行过滤,以便我可以显示数组colors
中的元素,只要它们在cars
中显示为值
var colors = ["blue","red","pink","yellow"];
var cars = [{"brand":"Ford","color":"blue"}
,{"brand":"Ferrari","color":"red"}
,{"brand":"Rolls","color":"blue"}];
var filteredColors = colors.filter(function(color) {
return cars.some(function(car) {
return car.color === color;
});
});
console.log(filteredColors);
我试图在Angular JS中应用它,这样做:
$scope.colors =["blue","red","pink","yellow"];
$scope.cars=[ {"brand":"Ford","color":"blue"}
,{"brand":"Ferrari","color":"red"}
,{"brand":"Rolls","color":"blue"}];
$scope.filteredColors = function() {
var colorsvar = $scope.colors;
var carsvar = $scope.cars;
return colorsvar.filter(function(color) {
return carsvar.some(function(car) {
return car.color === color;
});
});
};
然后在视图中:
<ul>
<li ng-repeat="n in colors | filter: filteredColors"> {{n}}
</li>
</ul>
结果应该是
但它没有恰当地过滤掉。请参阅work plunkr here欢迎任何帮助,谢谢!
答案 0 :(得分:1)
无需调用过滤器。只需在ng-repeat
<li ng-repeat="n in filteredColors()"> {{n}}
</li>
演示
var app = angular.module("myApp",[]);
app.controller("myCtrl",function($scope){
$scope.colors =["blue","red","pink","yellow"];
$scope.cars=[ {"brand":"Ford","color":"blue"}
,{"brand":"Ferrari","color":"red"}
,{"brand":"Rolls","color":"blue"}];
$scope.filteredColors = function() {
var colorsvar = $scope.colors;
var carsvar = $scope.cars;
return colorsvar.filter(function(color) {
return carsvar.some(function(car) {
return car.color === color;
});
});
};
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
<ul>
<li ng-repeat="n in filteredColors()"> {{n}}
</li>
</ul>
</div>
答案 1 :(得分:1)
您可以使用如下自定义过滤器,查看演示
<强>样本强>
var app = angular.module("myApp",[]);
app.controller("myCtrl",function($scope){
$scope.colors =["blue","red","pink","yellow"];
$scope.cars=[ {"brand":"Ford","color":"blue"}
,{"brand":"Ferrari","color":"red"}
,{"brand":"Rolls","color":"blue"}];
})
app.filter('myFilter', function() {
// the filter takes an additional input filterIDs
return function( filterColors, inputArray) {
var filtered = [];
angular.forEach(inputArray,function(key,value){
if(filterColors.includes(key.color) && !filtered.includes(key.color)) {
filtered.push(key.color);
}
})
return filtered;
};
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
<ul>
<li ng-repeat="n in colors | myFilter: cars track by $index"> {{n}}
</li>
</ul>
</div>
&#13;