programmer
programmer

Reputation: 1094

AngularJS bind a selected option from an array of objects to a model that stores the id only

I'm new to Angular and I'm in need of a sanity check. I have an object, $scope.myObject, that stores the id only,myObject.colorId, of a laundry list of types. Then I have an array of objects of the types,$scope.colors = [{id:1, name:"blue"}, ...], that contains the id/name of each type. I have a <select> that is populated by these types and I want to bind them to the myObject.colorId but it's not working for me.

I can get it to work by storing the full type,eg { id: 3, name: 'white' }, as a property in myObject, but that doesn't seem right. Or maybe I'm such a newb that I'm missing something totally fundamental about AngularJS. :)

Here's a link to the plunker: http://plnkr.co/edit/iM5jjeqooQgAn6XGYoL2

Here's the gist of my code:

Controller:

$scope.colors = [
  { id: 9, name: 'black' }, 
  { id: 3, name: 'white' }, 
  { id: 5, name: 'red' }, 
  { id: 4, name: 'blue' }, 
  { id: 7, name: 'yellow' }];

// Works
$scope.myColor = $scope.colors[2]; // red

// Doesn't work, do I really have to keep
// track of the full color object in myObject
// like myObject.color = { id: 5, name: 'red' };
// and not simply the color id?
$scope.myObject = { colorId: 5 };

View:

<!-- Works -->
<select 
    ng-model="myColor" 
    ng-options="color.name for color in colors track by color.id">
</select>

<!-- Doesn't Work -->
<select 
    ng-model="myObject.colorId" 
    ng-options="color.name for color in colors track by color.id">
</select>

Upvotes: 2

Views: 976

Answers (2)

Mukund Kumar
Mukund Kumar

Reputation: 23211

use this code and see plunker:

<select ng-model="myObject.colorId" ng-options="color.id as color.name for color in colors">
</select>

Upvotes: 2

Deblaton Jean-Philippe
Deblaton Jean-Philippe

Reputation: 11398

track by is just used behind by angular to know how to bind scopes between each other. You can use it inside a ng-repeat when some value can be equals. eg : [1, 1, 3]

If you try to iterate through the previous array, it will fail because angular will track changes with the key being the value. This is in this case that track by id is useful.

In your case, you're not far from the solution :

<!-- Works -->
<select 
  ng-model="myColor" 
  ng-options="color.id as color.name for color in colors track by color.id">
</select>

Upvotes: 1

Related Questions