Ng-options displays an empty selected option, even if an ng model is defined

I created plunkr to emphasize the problem, perhaps because the ng-repeat source is a function, I'm not sure, but so far I have tried everything to solve this problem, and could not get itchy.

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); }); }); 
+6
source share
2 answers

The last thing I checked, Angular does not support the ability to bind array keys to the ng model via ng-options. You can, however, simulate 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; } 

Keep in mind that this will associate integers with your model, and not with 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; } 
+8
source

If you use the array as a model, then the model is a string, not a number. Therefore, you need to convert the number to a string. Just try

 $scope.model.selectedLocation = '1'; 
+13
source

Source: https://habr.com/ru/post/952108/


All Articles