【发布时间】:2016-01-22 07:27:11
【问题描述】:
我编写了以下 Angular 应用程序的概念验证,该应用程序允许人们投票选举美国总统。
<!DOCTYPE html>
<html ng-app="ElectionApp"">
<head>
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.4/angular.min.js"></script>
<script>
var ElectionApp = angular.module("ElectionApp", []);
var ElectionController = ElectionApp.controller("ElectionController", [function () {
// Pretend that this data came from an outside data-source.
this.candidates = {
"14837ac3-5c45-4e07-8f12-5771f417ca4c": {
name: "Alice",
gender: "female"
},"333eb217-c8d1-4b94-91a4-22a3770bbb22": {
name: "Bob",
gender: "male"
}
};
this.vote = function () {
// TODO: Record the user's vote.
};
}]);
</script>
</head>
<body ng-controller="ElectionController as ctrl">
Who would you like to elect President? <br />
<select
ng-model="ctrl.selection"
ng-options="person as person.name for (id, person) in ctrl.candidates | filter{gender:'female'}">
</select>
<input type="button" value="Vote!" ng-submit="ctrl.vote();" />
<h2>Candidate Profiles</h2>
<div ng-repeat="candidate in ctrl.candidates">
{{candidate.name}}, {{candidate.gender}}
</div>
</body>
</html>
我的投票应用会显示候选人姓名列表以及每位候选人的个人资料,在本例中,包括候选人的姓名和性别。
就本题而言,请假设可供选择的候选人名单是从远程数据源获取的,但将遵循与示例相同的格式。
假设在即将举行选举前不久,通过了一项宪法修正案,规定下一任美国总统必须是女性。假设数据源无法及时更新选举,老板对我说,“我听说用Angular,你可以使用过滤器任意选择数据源中的哪些项目出现在表单上。让它发生!”
根据我在网上看到的一些示例,我编写了上面的代码,但它不再显示任何候选者。我做错了什么?
如何使用 Angular 过滤器过滤选择列表中的选项?
【问题讨论】:
-
过滤后缺少 :
-
在做了更多研究之后,看起来同样的问题在 2 年前被问到:stackoverflow.com/questions/14788652。那里的答案是 Angular 不这样做,但我认为必须有一些合理的方法。
-
"我听说使用 Angular,您可以使用过滤器任意选择数据源中的哪些项目出现在表单上。实现它!"使用
ng-repeat而不是ng-options来呈现您的选项,这绝对是正确的。
标签: angularjs ng-options angularjs-ng-options