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

标签 javascript html angularjs angular-ngmodel ng-options

我有一个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/

相关文章:

javascript - firebase.initializeApp 在我的 dotenv 文件中找不到 API key 。 (下一个.js)

javascript - 如何在 javascript 中为 Array 制作重复原型(prototype)方法的原型(prototype)

html - float 时垂直对齐 div

javascript - 从左向右移动div然后停止

javascript - RxJS 可观察到的.concat : How to know where next result came from?

javascript - Angular JS - 按ng-repeat表上的entry_date排序仅按月和日而不是年排序

javascript - 改变计算属性中的数据也更改了 vuex 存储中的数据 : why? 感谢任何帮助

javascript - 根据下拉列表中的选择动态初始化未保存父对象的子记录

javascript - scrollIntoView() 不适用于 IOS safari 和 chrome?

angularjs - 我应该如何在 jasmine 单元测试中访问元素的 angularjs $ngModelController?