Search code examples
angularjsng-options

How to set the ng-options default using object?


If i set a value dropdown value as a object is not working as expected.

for Example : HTML:

<select ng-model="selected" ng-options="lst as lst.name for lst in list"></select>

JS:

$scope.list=[{'name':'Person-1','age':23},
  {'name':'Person-2','age':14},
  {'name':'Person-3','age':32},
  {'name':'Person-4','age':34},
  {'name':'Person-5','age':67},
  {'name':'Person-6','age':12}];

   $scope.selected = {'name':'Person-3','age':32};

If i assign a value as $scope.selected = $scope.list[0] is working fine. But now how can i assign a object to select.

i have attached the plunker link : http://plnkr.co/edit/WJo0W688s5NDN7kZYOPR?p=preview


Solution

  • It's because the object which you are assigning is not there in $scope.list. However it looks same but it's a different object. $scope.list[0] is working because it points to the same object reference which $scope.list is having.

    See updated plunker so that you can understand.

    Updated

    If you have objects then you need to iterate over the $scope.list by comparing properties and find index of appropriate object and use that index to assign selected object like.

    $scope.selected = $scope.list[matchIndex]