【问题标题】:keeping track of nested ng-repeat index's跟踪嵌套的 ng-repeat 索引
【发布时间】:2017-04-12 14:59:45
【问题描述】:

所以我有一个这样的嵌套 ng-repeat:

<div ng-repeat="data in flow" ng-init="$flowIndex = $index">

    Index: {{ $index }}
    <div ng-click="flow.splice($index, 1)">Delete me</div>

    <div ng-repeat="inside_data in flow[$flowIndex]">
        Inside index: {{ $index }}
    </div>

</div>

我希望能够删除我的$flowIndex 中的索引。但是,如果我有这样的事情:

0 
1
2
3

然后我删除索引2。如果我去删除索引3,则找不到它,因为 ng-init 变量仍然在索引 3 处,但实际上不在索引 2 处。

有人知道解决办法吗?

【问题讨论】:

  • 当您使用 ng-click 删除索引 2 时,它应该触发一个摘要循环,该循环将重新执行 ng-repeat 并导致以前索引 3 的项目具有索引 2。你是在 AngularJS 之外做一些事情以使摘要不会出现?

标签: javascript angularjs


【解决方案1】:

我相信你可以像这样得到父索引:

$parent.$index

正如这个答案中提到的:passing 2 $index values within nested ng-repeat

这样您就不必担心变量与当前状态不同步。

【讨论】:

    【解决方案2】:

    你可以去掉$flowIndex,这不是必须的,你可以改用$parent.$index,当你使用ngRepeat时,它会创建一个子作用域,$index是该作用域的一部分。还可以考虑将删除逻辑移到控制器中。

    控制器:

    $scope.delete = function ($index) {
        $scope.flow.splice($index, 1);
    };
    

    HTML:

    <div ng-repeat="data in flow">
    
        Index: {{ $index }}
        <div ng-click="delete($index)">Delete me</div>
    
        <div ng-repeat="inside_data in flow[$index]">
            Inside index: {{ $parent.$index }} -> {{ $index }}
        </div>
    </div>
    

    【讨论】:

    • 这很好,但是我发现ng-repeat 仍然应该是$index 而不是$parent.$index
    • @bryan 你是对的,它当时属于父范围。因此,不需要用户$parent,因为它已经在$parent 上。我已经更新了我的答案。
    【解决方案3】:

    我刚刚使用一些虚拟数据字符串测试了您的类似代码,并且删除似乎有效。我对您的代码进行了一些更新,以便更好地对其进行分析。

    // Code goes here
    
    var myApp = angular.module('myApp',[]);
    
    myApp.controller('MyController', ['$scope', function($scope) {
      $scope.flow = [
        ["test01","test02","test03"],
        ["test11","test12","test13"],
        ["test21","test22","test23"],
        ["test31","test32","test33"],
        ["test41","test42","test43"]
      ]
      ;
    }]);
    <!DOCTYPE html>
    <html>
    
      <head>
        <script data-require="angularjs@1.5.8" data-semver="1.5.8" src="//opensource.keycdn.com/angularjs/1.5.8/angular.min.js"></script>
        <link rel="stylesheet" href="style.css" />
        <script src="script.js"></script>
      </head>
    <body ng-app="myApp">
      <section ng-controller="MyController">
      <div ng-repeat="data in flow">
      
          Index: {{ $index }}
          <div ng-click="flow.splice($index, 1)">Delete me [{{ $index }}]</div>
      
          <div ng-repeat="inside_data in flow[$index]">
              Inside index: {{ $index }} : {{ inside_data }}
          </div>
          <hr>
      </div>
    </section>
    </body>
    </html>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-06-18
      • 1970-01-01
      • 2014-12-31
      • 1970-01-01
      • 1970-01-01
      • 2023-04-01
      • 1970-01-01
      相关资源
      最近更新 更多