NG-如果造成$父。$索引设置为$指数设置为、索引、指数、NG

2023-09-13 03:22:24 作者:淺淺壹笑

我有一个NG-器使用它所包含嵌套NG-中继器。在嵌套直放站我试图跟踪父母$索引值,这工作正常。然而,当我引入纳克 - 如果在具有至$父。$索引参考相同的元素,父母索引设置为孩子的索引。在这个任何想法?在code运行。一个例子是,我点击父0指数1,并得到索引1父1为指标。

的JavaScript

  VAR对myApp = angular.module('对myApp',[]);myApp.controller('CTRL',函数($范围){  $ scope.arr = [[A,B,C],[D,F,E],[F,H,I]];  $ scope.logIndex =功能(索引,父母){    的console.log(索引:+指数+,家长:+父母);  };}); 

HTML

 < UL>  <李NG重复=我在改编>    < UL>      <李NG重复=&GT在我J;         <跨度NG点击=logIndex($指数,$父$指数)。NG-IF =$指数大于0> {{Ĵ}}< / SPAN>      < /李>    < / UL>  < /李>< / UL> 

解决方案 元数据管理 动态表单设计器在crudapi系统中完整实现

这是因为 NG-如果创建的元素对孩子的范围,所以 $父实际上是它的直接NG-repeat的子范围,而不是父之一,而$指数再次从其直接父继承了相同的$指数(即第二次NG-repeat的childscope)。您可以使用 NG-INIT NG-重复别名的特殊属性和使用该财产,而不是使用$父。

 <李NG重复=我ARRNG-的init =parentIndex = $指数>    < UL>      <李NG重复=&GT在我J;         <跨度NG点击=logIndex($指数,parentIndex)NG-IF =$指数大于0> {{Ĵ}}< / SPAN>      < /李>    < / UL>   < /李> 

演示

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>

解决方案

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