Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
240 views
in Technique[技术] by (71.8m points)

javascript - ng-selected not working in select element

I have a bound select

<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>  

but when both c.CollegeName == collegeSelection.CollegeName match the item still isn't selected. Documentation doesn't seem to help. Any ideas?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

ng-selected should be used in the <option> tag, not in the <select> tag. Take a closer look at its doc and the example.

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.

I created a very simple plunk to demonstrate the "selected" feature in select directive.

More details:

AngularJS uses ngModel directive to enable "two-way data binding" between your model and UI elements.

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];

And the HTML looks like:

<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.

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...