Search code examples
angularjsng-options

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:

  • set ng-model to the default option object and have it be automatically selected in the dropdown.

Solution

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