我有一个select
,我想使用ng-options
来填充它。选项的来源不是数组
,而是对象
。到目前为止一切顺利。
这个select
也有ng-model
。这意味着当模型的属性获取值时,选择需要根据该值更改所选的选项
。
问题是所选的选项
始终是第一个(空`选项),如本演示所示:
var app = angular.module('app', []);
app.controller('MainCtrl', function($scope) {
$scope.resourceList = {"0":"Unknown","1":"ILS","2":"USD","3":"AUD","4":"GBP","5":"JPY"};
$scope.resources = {
type: 3
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js"></script>
<div ng-app="app" ng-controller="MainCtrl">
{{resources.type}}
<select ng-model="resources.type" ng-options="key as value for (key, value) in resourceList track by key"></select>
<button data-ng-click="resources.type = '4'">Replace</button>
</div>
更新:我尝试了resources.type = '4'
和resources.type = 4
,但它们都不起作用。
注意:我在这里阅读了很多类似主题的问题,但没有找到此特定问题的答案,因此,请在将其标记为重复之前再次阅读该问题。
最佳答案
您需要使用track by $index
而是在你的 [ng-repeat]
中
var app = angular.module('app', []);
app.controller('MainCtrl', function($scope) {
$scope.resourceList = {"0":"Unknown","1":"ILS","2":"USD","3":"AUD","4":"GBP","5":"JPY"};
$scope.resources = {
type: 3
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js"></script>
<div ng-app="app" ng-controller="MainCtrl">
{{resources.type}}
<select ng-model="resources.type" ng-options="key as value for (key, value) in resourceList track by $index"></select>
<button data-ng-click="resources.type = '4'">Replace</button>
</div>
关于javascript - 对象中的 ng-options 和 ng-model 作为数据源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34496746/