ng-options displays blank selected option, even though ng-model is defined
angularjs, angularjs-ng-repeat
Solution
Last I checked, Angular does not support the ability to bind array keys to ng-model via ng-options. You can, however, mimic this behavior using an object hash:
menu.html:
<div ng-controller="menuCtrl">
<select ng-model="model.selectedLocation" ng-options="x.value as x.label for x in model.locations()">
</select>
</div>
script.js:
$scope.model.locations = function(){
var loc = [{
value: 0,
label: 'Dublin'
}, {
value: 1,
label: 'Stockholm'
}, {
value: 2,
label: 'New Jersey'
}];
$scope.model.selectedLocation = 1; // Set default value
return loc;
}
Bear in mind that this will bind the integers to your model, and not the cities themselves. If you want your model value to be `Dublin`, `Stockholm`, or `New Jersey`, simply do:
menu.html:
<div ng-controller="menuCtrl">
<select ng-model="model.selectedLocation" ng-options="name for name in model.locations()">
</select>
</div>
script.js:
$scope.model.locations = function(){
var loc = ['Dublin', 'Stockholm', 'New Jersey'];
$scope.model.selectedLocation = 'Dublin'; // Set default value
return loc;
}
Problem
I have created a plunkr to emphasize the problem, perhaps it's because the source of the ng-repeat is a function, I am not sure, but so far I've tried everything in order to solve this, and couldn't mange. plunkr: http://plnkr.co/edit/qQFsRM?p=preview HTML ``` <html> <head> <script data-require="angular.js@1.2.0-rc1" data-semver="1.2.0-rc1" src="http://code.angularjs.org/1.2.0rc1/angular.js"></script> <link rel="stylesheet" href="style.css" /> <script src="script.js"></script> </head> <body ng-app='myApp' ng-controller='mainCtrl'> <ng-include src="'menu.html'"> </ng-include> </html> ``` Script ``` var app = angular.module('myApp', []); app.controller('mainCtrl', function($scope, $httpBackend){ $scope.model = {}; $scope.model.myJobs = {}; $scope.refreshJobs = function(){ } }); app.controller('menuCtrl', function($scope){ $scope.model.locations = function(){ var loc = []; loc[1] = 'Dublin'; loc[2] = 'Stockholm'; loc[3] = 'New Jersy'; $scope.model.selectedLocationDef = loc.indexOf('Dublin'); return loc; } $scope.model.selectedLocation = $scope.model.selectedLocationDef; $scope.$watch('model.selectedLocation', function(location){ $scope.refreshJobs(location); }); }); ```