ng-if Scope issue with nested ng-repeat

Scenario:

I have an ng-repeater with a nested ng-repeater. In the nested loop, I am trying to track the parents $index value. 

Javascript:

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

myApp.controller('ctrl', function($scope) {
 var json="[{\"Id\":1,\"Name\":\"test1\",\"Department\":\"department1\"},{\"Id\":2,\"Name\":\"test2\",\"Department\":
\"department2\"},{\"Id\":3,\"Name\":\"test3\",\"Department\":\"department1\"}]";
    $scope.data = JSON.parse(json);
    $scope.keys = ['Id', 'Name', 'Department'];
});

HTML:

<table class="table table-bordered table-striped">
    <thead>
        <tr>
            <th ng-repeat="key in keys">{{key}}</th>
        </tr>
    </thead>
    <tr ng-repeat="d in data">
        <td ng-repeat="key in keys">
            <input type="text" class="form-control" ng-model="data[$parent.$index][key]" />
        </td>
    </tr>
</table>
However, when I introduce an ng-if in the same element that has a reference to $parent.$index like
 <span ng-model="data[$parent.$index][key]" ng-if="key='Id'"></span>
 <input type="text" class="form-control" ng-model="data[$parent.$index][key]" ng-if="key!='Id'" />
the parents index is set to the child's index.

Solution:

This behaviour 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). So, we need to use ng-init to alias special properties of ng-repeat and use that property instead of using $parent. The above code should be as below
<table class="table table-bordered table-striped">
 <thead>
  <tr>
   <th ng-repeat="key in keys">{{key}}</th>
  </tr>
 </thead>
 <tr ng-repeat="d in data" ng-init="parentIndex=$index">
  <td ng-repeat="key in keys">
   <span ng-if="key=='Id'">{{data[parentIndex][key]}}</span>
   <input type="text" class="form-control" ng-model="data[parentIndex][key]" ng-if="key!='Id'" />
  </td>
 </tr>
</table>

Gopikrishna

    Blogger Comment
    Facebook Comment

0 comments:

Post a Comment