Angularjs select does not mark matching model as selected Angularjs select does not mark matching model as selected angularjs angularjs

Angularjs select does not mark matching model as selected


This is because each object has it's own $hashKey provided by Angular that Angular uses to determine whether they are the same. You're creating a new object (with a different $hashKey) on $scope.selectedState. The way you set it on $scope.selectedState2 is correct.

You can also use track by to make Angular track by state.id instead of the object's $hashKey:

<select ng-model="selectedState" ng-options="state.name for state in stateOptions track by state.id"></select>


If you are providing an object as the model which does not hold the reference to the existing list, then use track by with the unique value of your model, so that instead of using the custom unique $$hashKey, ng-options will use the property that you provide in the track by for tracking the ng-model that is being set.

  ng-options="state.name for state in stateOptions track by state.id"

Demo

Not only that it is useful in setting ng-model to any reference, but also it has a great deal of performance effectiveness as well especially when your list gets refreshed, the elements will not be removed and recreated, instead angular will just update the existing element.

Here is a very good example for this.


Angular Team stated this issue in the documentation for ngSelect here:

Note: ngModel compares by reference, not value. This is important when binding to an array of objects. See an example in this jsfiddle.

 $scope.options = [    { label: 'one', value: 1 },    { label: 'two', value: 2 }  ];  // Although this object has the same properties as the one in $scope.options,  // Angular considers them different because it compares based on reference  $scope.incorrectlySelected = { label: 'two', value: 2 };  // Here we are referencing the same object, so Angular inits the select box correctly  $scope.correctlySelected = $scope.options[1];