我正在尝试创建一个下拉列表,当我创建它时,我想按字段过滤。例如:
<!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>
&#13;
在此示例中,我如何按difficulty
进行过滤?是否可以做类似
ng-options="x.cost for x in costs where x.difficulty >= 3"
答案 0 :(得分:3)
使用这样的自定义filter
:
$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>
答案 1 :(得分:0)
有多种方法可以实现这一目标。 - 使用自定义过滤器 - 在控制器级别过滤列表并相应地将其绑定到视图。
这是你能做的。
var app = angular.module("sampleApp", []);
app.controller("sampleController", ["$scope",
function($scope) {
$scope.data = "Hello";
$scope.difficulty = 3;
$scope.costs = [{
'cost': 1,
'difficulty': 3
}, {
'cost': 2,
'difficulty': 2
}, {
'cost': 3,
'difficulty': 3
}];
$scope.filteredCosts = $scope.costs.filter(function(item) {
return item.difficulty >= 3
});
}
]);
app.filter("difficultyFiler", function() {
return function(costs, difficulty) {
return costs.filter(function(item) {
return item.difficulty >= difficulty
});
}
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular.min.js"></script>
<div ng-app="sampleApp">
<div ng-controller="sampleController">
<select ng-model="cost">
<option ng-repeat="item in costs">
{{item.cost}}
</option>
</select>
<select ng-model="cost">
<option ng-repeat="item in filteredCosts">
{{item.cost}}
</option>
</select>
<input type="text" ng-model="difficulty" />
<select ng-model="cost">
<option ng-repeat="item in costs | difficultyFiler : difficulty">
{{item.cost}}
</option>
</select>
</div>
<p>This example shows how to fill a dropdown list using the ng-options directive.</p>
</div>
</div>
&#13;