Alexander Matusiak
Alexander Matusiak

Reputation: 1828

AngularJS: Setting selected option in dropdown

I'm assigning an array of 'types' to a dropdown. When a user selects a value in the dropdown, I save it off to a cookie.

The code where I'm updating the ng-model:

$scope.typeItem = $cookieStore.get('typeItem');

This is the dropdown itself:

<select class="transmission-option-width" ng-model="typeItem" 
  ng-options="t as t.Type for t in transmissionTypes" ng-change="update()"></select>

I set a break point, and $scope.typeItem has a value, but the select is not being set. Any idea what I'm doing wrong here?

Upvotes: 0

Views: 774

Answers (3)

Anthony Chu
Anthony Chu

Reputation: 37560

The object you're getting back from the cookie store...

$scope.typeItem = $cookieStore.get('typeItem');

while it might have the same properties as one of the items in $scope.transmissionTypes, it's actually an entirely different object. Because angular does the comparison by reference, it can't find a matching object in $scope.transmissionTypes and the dropdown is not set.

Upvotes: 1

Dayan Moreno Leon
Dayan Moreno Leon

Reputation: 5435

i think you misted this part of the docs

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

try to traverse your array and assign the element in the array holding the same value to your model variable

Upvotes: 0

Sam Barnum
Sam Barnum

Reputation: 10744

Is t.Type a numeric value? That might prevent angular from treating the selected value as equal to the option value.

Might be easiest to convert $scope.typeItem to a numeric value after getting it from the $cookieStore.

Upvotes: 0

Related Questions