質問

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.
役に立ちましたか?

解決

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.

他のヒント

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'

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top