ng-if 导致 $parent.$index 被设置为 $index [英] ng-if causing $parent.$index to be set to $index

查看:35
本文介绍了ng-if 导致 $parent.$index 被设置为 $index的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 ng-repeater,其中包含一个嵌套的 ng-repeater.在嵌套转发器中,我试图跟踪父 $index 值,这很好用.但是,当我在引用 $parent.$index 的同一元素中引入 ng-if 时,父索引被设置为子索引.对此有何想法?代码在此处运行.例如,我单击父 0 的索引 1 并获取索引 1 父 1 作为索引.

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>

推荐答案

那是因为 ng-if 在元素上创建了一个子作用域,所以 $parent 实际上是它的直接 ng-repeat 的子作用域,而不是父作用域,并且 $index 又是从其直接父级(即第二个 ng-repeat 的子作用域)继承的相同 $index.您可以使用 ng-init 为特殊属性设置别名ng-repeat 并使用该属性而不是使用 $parent.

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>

演示

这篇关于ng-if 导致 $parent.$index 被设置为 $index的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆