javascript - orderby 和 track by $index 在 AngularJS 中不起作用

标签 javascript html angularjs

我已经订购了一个列表并使用了track by $index。但似乎列表没有排序。

<div ng-controller="MyCtrl">
  <div ng-repeat="rfi in rfiList | orderBy:['name', 'status'] track by $index">
    <p>
      {{rfi.name}}==>{{rfi.status}}
      <button ng-click="search($index)">OK      
     </button>
    </p>
  </div>
</div>

JavaScript 部分是

var myApp = angular.module('myApp', []);

function MyCtrl($scope) {
  $scope.rfiList = [{
      name: 'GHI',
      status: true
    },
    {
      name: 'GHI',
      status: false
    },
    {
      name: 'DEF',
      status: true
    },
    {
      name: 'DEF',
      status: false
    },
    {
      name: 'ABC',
      status: true
    },
    {
      name: 'JKL',
      status: true
    }
  ];

  $scope.search = function(index) {
    alert('Index is=' + index + ' and value is=' + $scope.rfiList[index].name + '-->' + $scope.rfiList[index].status);
  };
}

这里发生的情况是,在 search 方法中,rfiList[index] 在更改列表顺序后没有获取值。

列表排序后如何获取带有索引的值?

这是 jsfiddle 中的代码

最佳答案

试试这个:

var myApp = angular.module('myApp', []);

function MyCtrl($scope) {
  $scope.rfiList = [{
      name: 'GHI',
      status: true
    },
    {
      name: 'GHI',
      status: false
    },
    {
      name: 'DEF',
      status: true
    },
    {
      name: 'DEF',
      status: false
    },
    {
      name: 'ABC',
      status: true
    },
    {
      name: 'JKL',
      status: true
    }
  ];

  $scope.search = function(index,rfi) {
    alert('Index is=' + index + ' and value is=' + rfi.name + '-->' + rfi.status);
  };
}

在你的html中

<div ng-controller="MyCtrl">
  <div ng-repeat="rfi in rfiList | orderBy:['name', 'status'] track by $index">
    <p>
      {{rfi.name}}==>{{rfi.status}}
      <button ng-click="search($index, rfi)">OK      
     </button>
    </p>
  </div>
</div>

关于javascript - orderby 和 track by $index 在 AngularJS 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51605593/

相关文章:

angularjs - 使用 AngularJS HTML5 模式重新加载页面会给出错误的 GET 请求

javascript - ListView 与 NumericTextBox 数据初始化

javascript - 使用 renderDepth 和 Three.js 在顶部渲染对象

javascript - 使用 onClick 淡入淡出过渡

Javascript 将 switch 的大小写绑定(bind)到 html 按钮

css - 为什么我的 div 不能并排 float ?

android - Android 中 HTML 的 <label> 是什么?

html - 填满 1 行上的所有内容

javascript - Angular 2 - 根据页面切换指令组件

javascript - Angular $http 在 404 上调用成功