我有select
我希望使用ng-options
填充它。选项的来源不是array
,而是object
。到目前为止一切都很好。
此select
也有ng-model
。这意味着当模型的属性获得值时,select需要根据值更改选定的option
。
问题是所选的option
始终是第一个(null`选项),就像在这个演示中一样:
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
都尝试过,但都没有。
注意:我在这里阅读了很多类似主题的问题,但没有找到这个特定问题的答案,所以请在将此标记为重复之前再次阅读该问题。< / p>
答案 0 :(得分:2)
您需要在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>