How do I set the value property in AngularJS' ng-options?

后端 未结 27 1330
感动是毒
感动是毒 2020-11-22 08:17

Here is what seems to be bothering a lot of people (including me).

When using the ng-options directive in AngularJS to fill in the options for a &

27条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-22 08:48

    A year after the question, I had to find an answer for this question as non of these gave the actual answer, at least to me.

    You have asked how to select the option, but nobody has said that these two things are NOT the same:

    If we have an options like this:

    $scope.options = [
        { label: 'one', value: 1 },
        { label: 'two', value: 2 }
      ];
    

    And we try to set a default option like this:

    $scope.incorrectlySelected = { label: 'two', value: 2 };
    

    It will NOT work, but if you try to select the option like this:

    $scope.correctlySelected = $scope.options[1];
    

    It will WORK.

    Even though these two objects have the same properties, AngularJS is considering them as DIFFERENT because AngularJS compares by the reference.

    Take a look at the fiddle http://jsfiddle.net/qWzTb/.

提交回复
热议问题