ng-selected 在选择元素中不起作用 [英] ng-selected not working in select element
问题描述
我有一个绑定选择
<select ng-model="collegeSelection" ng-options="c as c.CollegeName for c in colleges" ng-selected="c.CollegeName == collegeSelection.CollegeName" name="selectCollege" id="selectCollege"></select>
但是当 c.CollegeName ==collegeSelection.CollegeName 都匹配时,项目仍然没有被选中.文档似乎没有帮助.有任何想法吗?
but when both c.CollegeName == collegeSelection.CollegeName match the item still isn't selected. Documentation doesn't seem to help. Any ideas?
推荐答案
ng-selected
应该用在 标签中,而不是
标签中>
标签.仔细查看它的 doc 和示例.
ng-selected
should be used in the <option>
tag, not in the <select>
tag. Take a closer look at its doc and the example.
因为select
指令对所选选项的确定是基于ngModel
.因此,一旦您删除 ng-selected="c.CollegeName ==collegeSelection.CollegeName"
,您的代码应该可以工作.
Because the select
directive's determination of the selected option is based on ngModel
. Therefore, once you remove ng-selected="c.CollegeName == collegeSelection.CollegeName"
, your code should work.
我创建了一个非常简单的 plunk 来演示 select 中的selected"功能代码> 指令.
I created a very simple plunk to demonstrate the "selected" feature in select
directive.
AngularJS 使用 ngModel
指令在模型和 UI 元素之间启用双向数据绑定".
AngularJS uses ngModel
directive to enable "two-way data binding" between your model and UI elements.
在select"的情况下,您指定为 <select ng-model="collegeSelection" ...>
的模型 collegeSelection
是 选定项目.这意味着如果用户从页面的下拉列表中选择一个项目,collegeSelection
将被设置为该项目;和,如果您将 collegeSelection
设置为您的 javascript 代码中的一个项目,AngularJS 将确保相应的 被选中.
In the case of "select", the model collegeSelection
you specified as <select ng-model="collegeSelection" ...>
is the selected item. Which means if an user selects an item from the dropdown on the page, collegeSelection
will be set to that item; and, if you set collegeSelection
to an item in your javascript code, AngularJS will make sure that the corresponded <option>
is selected.
假设您的控制器中有以下代码:
Say you have the following code in your controller:
$scope.colleges = [
{id: 0, name: 'a'},
{id: 1, name: 'b'},
{id: 2, name: 'c'}
];
$scope.collegeSelection = $scope.colleges[0];
HTML 如下所示:
<select ng-model="collegeSelection" ng-options="c as c.name for c in colleges"></select>
就是这样!如果您运行代码,将选择大学数组中的第一所大学.
That's it! The first college in the colleges array will be selected if you run the code.
记住collegeSelection
是选择的选项,不管是因为用户在UI上选择了一个项目,还是你在javascript中选择了一个项目.
Just remember collegeSelection
is the selected option, no matter it's because user selected an item on the UI, or you selected an item in javascript.
这就是双向数据绑定的工作原理.
That's how two-way data binding works.
这篇关于ng-selected 在选择元素中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!