Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
170
rated 0 times [  173] [ 3]  / answers: 1 / hits: 13470  / 10 Years ago, sun, september 7, 2014, 12:00:00

I have a problem with my ngModel in select not showing as selected. Both id and name are matching but its not working, see selectedState. Pointing model to the actual object within options array works, see selelectedState2. No idea whats going on ...



Fiddle:
http://jsfiddle.net/fedorsmirnoff/b49n4Ldp/2/



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

<select ng-model=selectedState2 ng-options=state.name for state in stateOptions></select>

function MainCtrl($scope) {
$scope.stateOptions = [
{id: 1, name: Alaska},
{id: 2, name: Montana},
{id: 3, name: Nebraska},
{id: 4, name: Texas}
]

$scope.selectedState = {id: 2, name: Montana};

$scope.selectedState2 = $scope.stateOptions[1];

}

More From » angularjs

 Answers
2

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>

[#42667] Friday, September 5, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
tyriquehenryq

Total Points: 248
Total Questions: 81
Total Answers: 105

Location: Bermuda
Member since Thu, Apr 20, 2023
1 Year ago
tyriquehenryq questions
;