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
286 views
in Technique[技术] by (71.8m points)

Setting default value in select drop-down using Angularjs

I have an object as below. I have to display this as a drop-down:

var list = [{id:4,name:"abc"},{id:600,name:"def"},{id:200,name:"xyz"}]

In my controller I have a variable that carries a value. This value decided which of the above three items in the array will be selected by default in the drop-down:

 $scope.object.setDefault = 600;

When I create a drop-down form item as below:

<select ng-model="object.setDefault" ng-options="r.name for r in list">                 

I face two problems:

  1. the list is generated as

    <option value="0">abc</option>
    <option value="1">def</option>
    <option value="2">xyz</option>
    

    instead of

    <option value="4">abc</option>
    <option value="600">def</option>
    <option value="200">xyz</option>
    
  2. No option gets selected by default even though i have ng-model="object.setDefault"

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Problem 1:

The generated HTML you're getting is normal. Apparently it's a feature of Angular to be able to use any kind of object as value for a select. Angular does the mapping between the HTML option-value and the value in the ng-model. Also see Umur's comment in this question: How do I set the value property in AngularJS' ng-options?

Problem 2:

Make sure you're using the following ng-options:

<select ng-model="object.item" ng-options="item.id as item.name for item in list" />

And put this in your controller to select a default value:

object.item = 4

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

...