简体   繁体   中英

angularjs select default value using ng-options

1st question:

How do I set default value using ng-option when my data is not an array? it's easy if the item is array, I simply can do

select = $scope.items[0];

Here is the Demo

2nd question:

  <select ng-model="selected" ng-options="name for (name, value) in items"></select>

I actually don't know how this work ^

and in my controller I have key-value object like this

 $scope.items = {
    'one': 30,
    'two': 27,
    'three': 50,
    'four': 15,
    'five': 27,
    'six': 30
   };

Solution for

Question 1:

If $scope.items is not an array but an object then

select = $scope.items.one; // to select first

OR

select = $scope.items['one']; // to select first

Question 2:

in your code

 <select ng-model="selected" ng-options="name for (name, value) in items"></select>

and in JS

$scope.secleted = $scope.items['one']

(name, value) in items will return an array of name and values (array of key value pairs). You can map the values with the name . That's why it's working

When the values in the object are primitive types (as in your case), angular compares by value rather than reference. So:

$scope.selected = 30;

or:

$scope.selected = $scope.items['one'];

works.

If the values are non-primitive then I suggest using "track by" to track by something else than object equality.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM