ng-if causing $parent.$index to be set to $index

旧城冷巷雨未停 提交于 2019-12-22 11:18:25

问题


I have an ng-repeater with a nested ng-repeater contained within it. In the nested repeater I am trying to track the parents $index value, this works fine. However, when I introduce an ng-if in the same element that has a reference to $parent.$index, the parents index is set to the child's index. Any ideas on this? The code is running here. An example would be, I click on index 1 of parent 0 and get index 1 parent 1 as indexes.

JavaScript

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

myApp.controller('ctrl', function($scope) {

  $scope.arr = [["a","b","c"],["d","f","e"],["f","h","i"]];

  $scope.logIndex = function(index, parent) {
    console.log("index: " + index + ", parent: " + parent);
  };

});

HTML

<ul>
  <li ng-repeat="i in arr">
    <ul>
      <li ng-repeat="j in i">
         <span ng-click="logIndex($index, $parent.$index)" ng-if="$index > 0">{{ j }}</span>
      </li>
    </ul>
  </li>
</ul>

回答1:


That is because ng-if creates a child scope on the element, so $parent is actually its immediate ng-repeat's child scope, not the parent one, and the $index is again the same $index inherited from its immediate parent (i.e second ng-repeat's childscope). You can use ng-init to alias special properties of ng-repeat and use that property instead of using $parent.

   <li ng-repeat="i in arr" ng-init="parentIndex=$index">
    <ul>
      <li ng-repeat="j in i">
         <span ng-click="logIndex($index, parentIndex)" ng-if="$index > 0">{{ j }} </span>
      </li>
    </ul>
   </li>

Demo



来源:https://stackoverflow.com/questions/26658679/ng-if-causing-parent-index-to-be-set-to-index

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!