bryan bryan - 7 days ago 5
Javascript Question

keeping track of nested ng-repeat index's

So I have a nested ng-repeat like so:

<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>


I want to be able to delete index in my
$flowIndex
. However if I have something like this:

0
1
2
3


And I delete index
2
. If I go and delete index
3
, it isn't found because ng-init variable still things its at index 3 but really its not at index 2.

Does anyone know a work around?

Answer

You can get rid of $flowIndex, it's not necessary, you can use $parent.$index instead, when you are using ngRepeat it creates a child scope and $index is part of that scope. Also consider moving your deleting logic into the controller.

Controller:

$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>
Comments