angular 中的列表更改时如何更新 $index

How to update $index when list changes in angular

我正在尝试在多级列表中实现键盘导航。 因此我尝试给列表中的每个项目一个唯一的 ID,比如 5.2.1(category.item.subitem).

我已经尝试了很多东西,比如 ng-init 对 ng-repeat 上的变量的索引,以及使用指令的其他方法,但到目前为止所有方法都有问题,当我更改列表时(删除项目示例)我的自定义索引没有更新!

我在这里做了一个简单的Plnkr: 您可以删除一个项目或子项目并看到 "real" 索引和自定义索引不相关。

http://plnkr.co/edit/BsRCNAqM7jWkeAJ9rkLN?p=preview

目前我有一个名为 customIndex 的自定义指令,它获取索引作为属性。

<li ng-repeat="subitem in item.subitem" custom-Index="$parent.$index+'.'+$index">

在指令中,我只是 $eval 属性:

.directive('customIndex', function(){
    return{
    restrict:'A',
    link: function(scope, el, attrs){
      scope.myIndex = scope.$eval(attrs.customIndex);
    }
  }
})

但是这个,就像我尝试过的所有其他解决方案一样,不起作用。

我想这一定是一种常见的问题。 有人对我有什么建议吗?

谢谢 马库斯

我觉得你把自己想得太复杂了。只尝试这段标记,不需要自定义指令或其他东西:

 <ul>
    <li ng-repeat="item in data">
      "Real"-index:{{$index}} | myIndex:{{myIndex = $index}}} | Item:{{item.itemName}} <button ng-click="data.splice(data.indexOf(item),1)">Del</button>
    <ul>
      <li ng-repeat="subitem in item.subitem">
        "Real"-index:{{$index}} | myIndex:{{myIndex = $parent.$index+'.'+$index}} | Subitem:{{subitem}} <button ng-click="item.subitem.splice(item.subitem.indexOf(subitem),1); ">Del</button>
      </li>
    </ul>
    </li>
  </ul>

ng-init 永远不会为你工作,因为它只在编译指令时执行。使用自定义指令它永远不会工作,因为范围项目将是您删除的项目并且您无权访问整个列表。

这是演示: http://plnkr.co/edit/Nr4cJ2m3JqI8NyLFnQhC?p=preview

所以,与此同时我找到了解决方案。也许不是最好的,但它确实有效。

我可以将所需的参数附加到指令属性,并在此属性上设置 $watch 以与 deleting/filtering 等引起的任何更改保持同步。 例如:

<div item-Index="[$parent.$index,$index,-1,$first, $last]"</div>

并且该指令在 link 函数中具有以下函数:

scope.$watch(attrs.itemIndex, function(value) {
            scope.itemIndex = value;
        });

现在每个项目都有一个定义的唯一索引。

多级键盘导航现在也可以了,但这超出了这个问题的范围。