gpt4 book ai didi

javascript - 对象中的 ng-options 和 ng-model 作为数据源

转载 作者:行者123 更新时间:2023-11-27 23:34:19 26 4
gpt4 key购买 nike

我有一个 select,我想使用 ng-options 来填充它。选项的来源不是数组,而是对象。到目前为止一切顺利。

这个select 也有ng-model。这意味着当模型的属性获得值时,select 需要根据值更改所选的 option

问题是所选的 option 始终是第一个(null `option),就像这个演示中一样:

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,但都不起作用。

注意:我在这里阅读了很多主题相似的问题,但没有找到该特定问题的答案,因此,请在将其标记为重复之前再次阅读该问题。

最佳答案

您需要在 [ng-repeat] 中使用 track by $index

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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com