此问题来自here
我想进行过滤,以便当 color.name 的值也作为 cars.color 中的值出现时,我可以显示它们
$scope.colors = [{"name":"blue","count":2},
{"name":"red","count":12},
{"name":"pink","count":5},
{"name":"yellow","count":2}];
$scope.cars=[ {"brand":"Ford","color":"blue", "seat":"pink"}
,{"brand":"Ferrari","color":"red", "seat":"pink"}
,{"brand":"Rolls","color":"blue","seat":"pink"}];
然后在 View 中:
<ul>
<li ng-repeat="n in colors | filter: filteredColors"> {{n}}
</li>
</ul>
结果应该是
我需要答案是没有 ES6,并且我需要将过滤器放在 Controller 中。请参阅 plunkr here 。提前致谢!
最佳答案
Controller :
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
$scope.colors = [{"name":"blue","count":2},
{"name":"red","count":12},
{"name":"pink","count":5},
{"name":"yellow","count":2}];
$scope.cars=[ {"brand":"Ford","color":"blue", "seat":"pink"}
,{"brand":"Ferrari","color":"red", "seat":"pink"}
,{"brand":"Rolls","color":"blue","seat":"pink"}];
$scope.filteredColors = function(color) {
var carsvar = $scope.cars;
for(var x = 0; x < carsvar.length; x++) {
if (color.name === carsvar[x].color) {
return true;
}
}
return false;
};
});
查看:
<!DOCTYPE html>
<html ng-app="plunker">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<link rel="stylesheet" href="style.css" />
<script data-require="<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="54353a33213835267a3e2714657a627a2c" rel="noreferrer noopener nofollow">[email protected]</a>" src="https://code.angularjs.org/1.6.6/angular.js" data-semver="1.6.6"></script>
<script src="app.js"></script>
</head>
<body ng-controller="MainCtrl">
<ul>
<li ng-repeat="color in colors | filter: filteredColors"> {{color.name}}
</li>
</ul>
</body>
</html>
关于javascript - Angular JS - 当一个数组中特定键中的值也显示为另一个数组中特定键中的值时进行过滤,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48190126/