我有一个非常简单的选择'元素使用角度模型绑定到值,如下所示:
<select ng-model="data.value">
<option ng-repeat="d in list" value="{{d.id}}">{{d.name}}</option>
</select>
绑定工作正常(我添加2个选择元素绑定到同一个var,当我更改其中一个时,第二个正确更改)。 我的问题是在加载到变量的初始值时没有正确设置select元素。
我的控制器代码是:
app.controller('MainCtrl', function($scope) {
$scope.list = [{id:1,name:'aaa'},
{id:2,name:'bbb'},
{id:3,name:'ccc'},
{id:4,name:'ddd'},
{id:5,name:'eee'}];
$scope.data = {value:2};
});
设置为this plunker的示例。
任何帮助将不胜感激。
答案 0 :(得分:0)
答案 1 :(得分:0)
我找到了解决方案: -
您可以使用ng-init初始化第一个。 ng-model可以从那里检查下面的Plunker for Work Out put
<!DOCTYPE html>
<html ng-app="plunker">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script>document.write('<base href="' + document.location + '" />');</script>
<link rel="stylesheet" href="style.css" />
<script data-require="angular.js@1.4.x" src="https://code.angularjs.org/1.4.9/angular.js" data-semver="1.4.9"></script>
<script src="app.js"></script>
</head>
<body ng-controller="MainCtrl">
<p>Hello {{name}}!</p>
<!-- first select:
<select ng-model="data.value">
<option ng-repeat="d in list" value="{{d.id}}">{{d.name}}</option>
</select> -->
<br/>
First Select :-
<select ng-init="data.value = list[0]"
ng-model="data.value"
ng-options="d.name for d in list">
</select>
<br/>
second select:
<select ng-init="data.value = list[0]"
ng-model="data.value"
ng-options="d.name for d in list">
</select>
<!--<select ng-model="data.value">-->
<!-- <option ng-repeat="d in list" value="{{d.id}}">{{d.name}}</option>-->
<!--</select>-->
<br/>
selected value: {{data.value}}
</body>
</html>
http://plnkr.co/edit/IydWDWosdLo6aSumb1ic?p=preview
注意: - 我刚刚更新了它 Plunker或只是用上面的代码替换你的代码!!
答案 2 :(得分:0)
我让你的plunker使用ng-options:
first select:
<select ng-model="data.value" ng-options="d.id as d.name for d in list">
</select>
<br/>
second select:
<select ng-model="data.value" ng-options="d.id as d.name for d in list">
</select>