bryan bryan - 3 months ago 17
Javascript Question

$parent.$index always returns 0

I have an

ng-repeat
inside another one and I am trying to find out the parents index.

Because it is being ordered after the fact, I can't do the typical

ng-repeat="(step_index, step) in flow"


Does anyone know why this would be happening?

<ul>
<li ng-repeat="step in flow | orderBy:'+step_number'">
<div class="step_container">
<div class="step_content">
<div ng-repeat="task in step.tasks">
<div class="task_container">
<div class="task_content">
{{ $parent.$index }} - {{ $index }}
</div>
</div>
</div>
</div>
</div>
</li>
</ul>

Answer

You can use ng-init="$parentIndex = $index" on your parent <li>, then call $parentIndex in the child ng-repeat

<ul>
    <li ng-repeat="step in flow | orderBy:'+step_number'" ng-init="$parentIndex = $index">
        <div class="step_container">
            <div class="step_content">
                <div ng-repeat="task in step.tasks">
                    <div class="task_container">
                        <div class="task_content">      
                            {{ $parentIndex }} - {{ $index }}
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </li>
</ul>
Comments