jqualls
jqualls

Reputation: 1503

ng-options predefined option Object

Have a look at my example http://plnkr.co/edit/21ewxVIaRm4IHyF3TgoD?p=preview

I need the option object to be stored as ng-model so i use for ng-options ng-options="m as m.name for m in list"

However, if i set ng-model manually as the object it does not select the correct option in the dropdown list by default. It stores the data correctly, but it only pre-selects an option if use this expression ng-options="m.name as m.name for m in list" but this stores a string on the model instead of the options object.

Am I doing something incorrectly?

Goal:

Upvotes: 0

Views: 1481

Answers (2)

As Davin Tryon has already mentioned, using track by is the correct way of doing it, however, I see some people using track by and 'as' in the same ng-options string, which will not work. using track by should also cater the need of using 'as'

Upvotes: 0

Davin Tryon
Davin Tryon

Reputation: 67296

Updated plunker.

For the version you are using (1.0.8), you would have to resolve the object using a loop:

$scope.selected = {
    name:"Something"
  }

  $scope.setSelected = function() {

    angular.forEach($scope.list, function(item) {

      if (item.name == $scope.selected.name) {

        $scope.selected = item;
      }
    })
  }

  $scope.setSelected();

More recent versions, have track by syntax supported in the ng-options. So you could write:

ng-options="m.name for m in list track by m.name"

And this would set the object that matches the predicate.

Upvotes: 1

Related Questions