即使定义了ng-model,ng-options也会显示空白选定选项

Ole*_*sov 7 angularjs angularjs-ng-repeat

我已经创建了一个强调问题的plunkr,也许是因为ng-repeat的来源是一个函数,我不确定,但到目前为止我已经尝试了一切以解决这个问题,并且无法管理.

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>
Run Code Online (Sandbox Code Playgroud)

脚本

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);
});

});
Run Code Online (Sandbox Code Playgroud)

zs2*_*020 13

如果使用数组作为模型,则模型是字符串而不是数字.所以你需要将数字转换为字符串.试一试

$scope.model.selectedLocation = '1';
Run Code Online (Sandbox Code Playgroud)


bib*_*ibs 9

最后我检查过,Angular不支持通过ng-options将数组键绑定到ng-model的功能.但是,您可以使用对象哈希模仿此行为:

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>
Run Code Online (Sandbox Code Playgroud)

的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;
}
Run Code Online (Sandbox Code Playgroud)

请记住,这会将整数绑定到模型,而不是城市本身.如果你希望你的模型值是Dublin,Stockholm或者New Jersey,简单地做:

menu.html:

<div ng-controller="menuCtrl">
  <select ng-model="model.selectedLocation" ng-options="name for name in model.locations()">
  </select>
</div>
Run Code Online (Sandbox Code Playgroud)

的script.js:

$scope.model.locations = function(){
  var loc = ['Dublin', 'Stockholm', 'New Jersey'];
  $scope.model.selectedLocation =   'Dublin'; // Set default value
  return loc;
}
Run Code Online (Sandbox Code Playgroud)