Petr Osipov
Petr Osipov

Reputation: 619

ng-repeat inside a directive template - access index

I have the following problem:

I have a custom directive, which shows one or more tables, by using ng-repeat inside the template string. Inside each table, several other custom directives are placed. I want these to know the index of the element used, but cant manage to get this done. My code looks like this now:

.directive('myStuffText', function ($rootScope){
    return {
        restrict: 'A',
        require: '^form',
        replace: true,
        scope: true,
        template:
        ......
        '<table border="1" ng-repeat="elt in myModel.newStuffList">
        ......

        '<tr>' +
        '<td colspan="3"><div my-add-some-editor my-element-index="$index"/></td>' +
        '</tr>' 
        '</table>',

        link: function (scope, elt, attrs){
            scope.cockpitPolicyModel.newPolicyList = [];
        }
    };

})

Independently from how I try, I always get the string $index or {{$index}} in the template function of the my-add-some-editor directive, not the value of it..

Edit - added the nested directive:

.directive('myAddSomeEditor', function($rootScope){
    return {
        restrict: 'A',
        require: '^form',
        scope: true,

        template: function ($scope, $attr){


            return 
            .....
            '<span id="myAddSomeEditor" name="myAddSomeEditor" class="form-control" my-generic-editor '+
            'my-input-mapping="myModel.someText"></span>'
            .....
            ;
            }
    };
})

Upvotes: 1

Views: 668

Answers (1)

Omri Aharon
Omri Aharon

Reputation: 17064

That probably happens because in your my-add-some-editor directive you have this definition in the isolate scope:

myElementIndex: '@'

That's why you're getting the literal string of what you're writing there in the HTML.

Change that to:

myElementIndex: '='

EDIT: Since you said you're not using isolated scope, try this in the parent directive: try doing my-element-index="{{$index}}". And this in the child directive's link function:

link: function (scope, elem, attr) {
    attr.$observe('index', function(val) {
      scope.index = val;
    });
}

Upvotes: 1

Related Questions