angularjs - 为什么无法通过 id 选择 'track by' 的 Angular ng-options

标签 angularjs

我有一个使用 ng-options 显示的对象数组,并使用 id 设置 ng-model。如果我在其上添加track by,则无法选择该项目,如果不添加,则工作正常,为什么?代码如下:

angular.module('myApp', [])
  .controller('MyController', ['$scope', function ($scope) {
    $scope.countryList = [{id: 1, name: 'China'}, {id: 2, name: 'America'}, {id: 3, name: 'England'}]
    $scope.country = 1;
  }]);
  
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.8/angular.js"></script>
<div class="container" ng-app="myApp">
  <div ng-controller="MyController">
      <p><select ng-model="country" ng-options="country.id as country.name for country in countryList"></select> no track by</p>
      <p><select ng-model="country" ng-options="country.id as country.name for country in countryList track by country.id"></select> have track by, can't selected by id</p>
  </div>
</div>

最佳答案

如上所述in this github issue - "ng-options track by and select as are not compatible"shown in this fiddle

“你不能将值作为集合标签与跟踪依据结合起来。你必须选择其中之一。”。

对于您的情况,选择应该是:

<select ng-model="country" ng-options="country as country.name for country in countryList track by country.id"></select>

在 JS 中

$scope.country = $scope.countryList[0];

JSFiddle here for your case .

选择的值将是对象,而不仅仅是 ID。

重点是,您必须在选择作为标签或按大小写轨道之间进行选择。

关于angularjs - 为什么无法通过 id 选择 'track by' 的 Angular ng-options,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40281793/

相关文章:

ajax - 使用 Angular js 登录 ajax 后清空 Passport session

javascript - AngularJS 奇怪的行为,NG-INCLUDE 导致整个页面重新加载

javascript - 在 Angular 中从 ng-change 运行 Javascript 函数

javascript - AngularJs:返回嵌套 $http 的 promise - 已经找到解决方案,但为什么它有效?

javascript - 监视 AngularJS 中对象的所有属性

javascript - 无法为 View 实例化 ngRoute

javascript - 从单独的文件调用 angular.module,找不到 Controller

javascript - Angular JS 中的 DOM 查询; $ (".myclass").each() 替代

javascript - AngularJS:装饰 $http

javascript - Bootstrap Angular.js Accordion 不会自动折叠