考虑下一个代码示例:
http://plnkr.co/edit/LA6fu1vdzRWFaQw6Zl6S?p=preview
<!DOCTYPE html>
<html ng-app="app">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script src="http://code.angularjs.org/1.1.5/angular.min.js"></script>
<script src="app.js"></script>
</head>
<body ng-controller="main">
<select novalidate="" ng-model="selectedItem" ng-options="item.id as item.name for item in items track by item.id"> </select>
</body>
</html>
var app = angular.module('app', [])
.controller('main', ['$scope',function($scope) {
$scope.items = [
{"id":0,"name":"a"},
{"id":1,"name":"b"},
{"id":2,"name":"c"},
{"id":3,"name":"d"}
];
$scope.selectedItem = 1;
}])
我希望在初始加载时选择元素会有一个&#34; b&#34;选择了选项,但它没有。我做错了什么?
答案 0 :(得分:1)
你需要:
使用AngularJS的更新版本(在您的脚本中将1.1.5
更改为1.6.10
)
删除track by item.id
,它用于ng-repeat
,而不是ng-options
这是一个有效的演示:
var app = angular.module('app', [])
.controller('main', ['$scope',function($scope) {
$scope.items = [
{"id":0,"name":"a"},
{"id":1,"name":"b"},
{"id":2,"name":"c"},
{"id":3,"name":"d"}
];
$scope.selectedItem = 1;
}])
<!DOCTYPE html>
<html ng-app="app">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.10/angular.js"></script>
</head>
<body ng-controller="main">
<select novalidate=""
ng-model="selectedItem"
ng-options="item.id as item.name for item in items">
</select>
{{selectedItem}}
</body>
</html>