Pregunta

I have the following ng-repeat HTML code:

<group ng-repeat="group in groups" groups="groups" group="group"></group>

Which works great for me at generating the groups from my object. The problem I am having is that $index though doesn't work inside of this directive.

So in the Group Template:

<div>
{{$index}} - {{group.Name}} {{group.Target}}
</div>

The $index is always undefined.

Here is the directive:

app.directive('group', function () {
    return {
        restrict: 'E',
        scope: {
            groups: '=',
            group: '='
        },
        templateUrl: '../../Content/templates/RecruitingGroups/Group.html',
        link: function (scope, el) {
            //Set Rules
            if (scope.group.Rule) {
                scope.ruleRules = scope.group.Rule.Rules;
            }
        }
    }
});
¿Fue útil?

Solución

Your directive uses an isolate scope. To access $index inside the parent scope you need to use $parent:

<div>
    {{$parent.$index}} - {{group.Name}} {{group.Target}}
</div>

Fiddle

Otros consejos

Instead of $index you can define current key in your ng-repeat

<group ng-repeat="(key, group) in groups" groups="groups" group="group"></group>

<div>
  {{key}} - {{group.Name}} {{group.Target}}
</div>

Here this key will do the same thing as $index
$index will refer to our parent DOM but key will refer to ng-repeat parameter only
So sometime to access $index in parent scope you have to use $parent.$index and instead of $index you can use key also

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top