In an Angular.js application we are building I had the following situation:
I have an array of option objects containing a label and a value that is used as input for a select list. On my controller I want to bind to the selected value (and not to the selected object!).
Here is the controller:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict'; | |
(function (app) { | |
var sampleController = function ($scope) { | |
$scope.selectedValue = 2; | |
$scope.options = [ | |
{ label: 'one', value: 1 }, | |
{ label: 'two', value: 2 } | |
]; | |
app.controller('sampleController', ['$scope',sampleController]); | |
}(angular.module('sampleApp'))); | |
First I had the following code in the view:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<select ng-model="selectedValue" | |
ng-options="opt.label for opt in options track by opt.value"> | |
</select> | |
The value selected is {{ selectedValue }}. | |
The above code resulted in the selectedValue set to the complete option object and not to the option.value property.
To fix it, I had to update the view code to the following:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<select ng-model="selectedValue" | |
ng-options="opt.value as opt.label for opt in options"> | |
</select> | |
The value selected is {{ selectedValue }}. |