Angular (1.x) - 从代码中以编程方式访问 NG-REPEAT

Angular (1.x) - Programmatically access NG-REPEAT from code

我正在尝试为仍然使用 angular 1.x 的旧项目设置热键,我尝试添加的其中一个功能是 select 第一行来自使用 NG-REPEAT 创建的 table。我已经能够添加其他功能,例如将 selected 行向上/向下移动,因为我在 ng-click="setSelected(this)" 上传递了 selected 行,然后让我保存该行并使用 selectedRow.$$prevSibilingselectedRow.$$nextSibiling.

移动它

我很难弄明白的是如何从控制器设置 selectedRow

这是一个简单的例子:

http://plnkr.co/edit/6jPHlYwkgF5raRWt?open=lib%2Fscript.js

JS:

App.controller('ActivitiesCtrl', [function() {
  var vm = this;
  vm.selectedRow = "Not set";
  vm.activities = [
    {
      "id": 1,
      "code": "ABC",
      "person": "Joe"
    },
    {
      "id": 2,
      "code": "DFF",
      "person": "Sally"
    },
    {
      "id": 3,
      "code": "ABC",
      "person": "Sue"
    },
    {
      "id": 4,
      "code": "124",
      "person": "Sam"
    },
  ];
  vm.setSelected = function(row) {
    vm.selectedRow.selected = false;
    vm.selectedRow = row;
    vm.selectedRow.selected = true;
  }
  vm.moveNext = function() {
    vm.setSelected(vm.selectedRow.$$nextSibling)
  }
  vm.setFirst = function() {
    vm.setSelected("How do I set it...");
    // How to set it? vm.setSelected(?????)
  }
}]);

HTML:

<div ng-controller="ActivitiesCtrl as vm">
  <table>
    <thead>
      <th>Id</th>
      <th>Code</th>
      <th>Person</th>
    </thead>
    <tbody>
      <tr ng-repeat="activity in vm.activities track by activity.id" ng-click="vm.setSelected(this)" ng-class="{info: selected}">
        <td>{{activity.id}}</td>
        <td>{{activity.code}}</td>
        <td>{{activity.person}}</td>
      </tr>
    </tbody>
  </table>
{{vm.selectedRow | json}}
<hr />
<button ng-click="vm.setFirst()">Set First</button>
<button ng-click="vm.moveNext()">Next</button>
</div>

这里是 link 测试工作示例。

enter code here 
http://plnkr.co/edit/7mTvRB0ZlHOQwOIc?preview

您可以通过将数组中的实际对象设置为 selectedRow 而不是使用 this 来执行此操作,并通过检查 ng-[=27 中的 selectedRow === activity 来设置 class =].

这种方法不需要改变对象

<tr
    ng-repeat="activity in vm.activities track by activity.id"
    ng-click="vm.setSelected(activity)"
    ng-class="{info: vm.selectedRow == activity}"
>

然后您可以使用 Array#findIndex() 获取数组中的当前 selectedRow 索引,如果存在下一个索引,则使用它或返回到第一个索引。

对于 setFirst() 你只需使用 vm.activities[0]

vm.selectedRow = null;

vm.setSelected = function (row) {     
  vm.selectedRow = row;     
};

vm.moveNext = function () {
  const {selectedRow:curr, activities:act} = vm;
  if (curr !== null) {
    let idx = act.findIndex(e => e == curr) + 1;
    let next = act[idx] || act[0];        
    vm.setSelected(next);
  }      
};

vm.setFirst = function () {
  vm.setSelected(vm.activities[0]);
};

Working plunker