7

我创建了一个 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>

脚本

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

});
4

2 回答 2

13

如果您使用数组作为模型,则模型是字符串而不是数字。因此,您需要将数字转换为字符串。你试一试

$scope.model.selectedLocation = '1';
于 2013-08-20T14:08:55.853 回答
9

最后我检查了一下,Angular 不支持通过 ng-options 将数组键绑定到 ng-model 的能力。但是,您可以使用对象哈希来模仿这种行为:

菜单.html:

<div ng-controller="menuCtrl">
  <select ng-model="model.selectedLocation" ng-options="x.value as x.label for x in model.locations()">
  </select>
</div>

脚本.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;
}

请记住,这会将整数绑定到您的模型,而不是城市本身。如果您希望您的模型值为DublinStockholmNew Jersey,只需执行以下操作:

菜单.html:

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

脚本.js:

$scope.model.locations = function(){
  var loc = ['Dublin', 'Stockholm', 'New Jersey'];
  $scope.model.selectedLocation =   'Dublin'; // Set default value
  return loc;
}
于 2013-08-20T13:53:25.683 回答