Trouble With Angularjs And Select Binding Not Loading Default Values
I am having trouble with a
Solution 1:
Two issues:
- Compare strings to strings
- Be careful when using
select as
andtrack by
in the same expression.
JS
angular.module('defaultValueSelect', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.data = {
availableOptions: [
{id: '1', name: 'Option A'},
{id: '2', name: 'Option B'},
{id: '3', name: 'Option C'}
],
//USE this
selectedOption: '2'//NOT this//selectedOption: 2 //This sets the default value
};
}]);
HTML
<!-- remove 'track by option.id' --><selectname="mySelect"id="mySelect"ng-options="option.id as option.name for option
in data.availableOptions track by option.id"ng-model="data.selectedOption"></select>
From the Docs:
Be careful when using
select as
andtrack by
in the same expression.This will work:
<select ng-options="item as item.label for item in items track by item.id" ng-model="selected"> </select>
but this will not work:
<select ng-options="item.subItem as item.label for item in items track by item.id" ng-model="selected"> </select>
Solution 2:
As requested by OP, adding the comment as the answer.
If you remove the "track by option.id" from the ng-options as following, it should pre-select based on your model.
<select name="mySelect"id="mySelect"
ng-options="option.id as option.name for option in data.availableOptions"
ng-model="data.selectedOption"></select>
Check out the modified Plunker: http://plnkr.co/edit/b4ddyA5Q4jGNcJI1d8eW?p=preview
Post a Comment for "Trouble With Angularjs And Select Binding Not Loading Default Values"