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

时间:2015-12-28 16:03:03

标签: javascript html angularjs angular-ngmodel ng-options

我有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>

1 个答案:

答案 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>