I'm still getting the hang of Angular and I could really use a second opinion. The issue I'm facing is with an object called $scope.myObject
that only stores the id, myObject.colorId
, for a variety of types in a laundry list format. Then there's an array of objects representing these types,
$scope.colors = [{id:1, name:"blue"}, ...]
, each containing the id/name pair. I have a <select>
element filled with these types and I aim to bind them to the myObject.colorId
property, but it just doesn't seem to be working as intended.
I managed to make it function by saving the entire type object,eg { id: 3, name: 'white' }
, within myObject
, although it doesn't feel quite right. Maybe I'm missing some crucial understanding about AngularJS due to my beginner's status. :)
You can find the plunker here: http://plnkr.co/edit/iM5jjeqooQgAn6XGYoL2
This is the essence 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>