我创建了一个强调问题的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);
});
});
答案 0 :(得分:13)
如果使用数组作为模型,则模型是字符串而不是数字。所以你需要将数字转换为字符串。试试吧
$scope.model.selectedLocation = '1';
答案 1 :(得分: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>
的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;
}
请记住,这会将整数绑定到模型,而不是城市本身。如果您希望模型值为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>
的script.js:
$scope.model.locations = function(){
var loc = ['Dublin', 'Stockholm', 'New Jersey'];
$scope.model.selectedLocation = 'Dublin'; // Set default value
return loc;
}