我正在尝试创建一个下拉列表,当我创建它时,我想按字段进行过滤。例如:
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<select ng-model="cost" ng-options="x.cost for x in costs">
</select>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.costs = [{'cost': 1, 'difficulty' : 3}, {'cost': 2, 'difficulty' : 2}, {'cost': 3, 'difficulty' : 3}];
});
</script>
<p>This example shows how to fill a dropdown list using the ng-options directive.</p>
</body>
</html>
在此示例中,我将如何按难度
进行过滤?是否可以做类似的事情
ng-options="x.cost for x in costs where x.difficulty >= 3"
最佳答案
使用自定义过滤器
,如下所示:
$scope.myFilter = function(x) {
return x.difficulty >= 3;
}
并将其应用到 ng-options
中,如下所示:
<select ng-model="cost" ng-options="x.cost for x in costs | filter : myFilter">
</select>
下面的演示:
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.costs = [{
'cost': 1,
'difficulty': 3
}, {
'cost': 2,
'difficulty': 2
}, {
'cost': 3,
'difficulty': 3
}];
$scope.myFilter = function(x) {
return x.difficulty >= 3;
}
});
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<select ng-model="cost" ng-options="x.cost for x in costs | filter : myFilter">
</select>
</div>
<p>This example shows how to fill a dropdown list using the ng-options directive.</p>
</body>
</html>
关于javascript - 在for循环中过滤掉,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40309645/