Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ng-repeat in custom directive: Syntax Error: Token '$index' is unexpected

Tags:

angularjs

In AngularJS, this fails with an error:

<my-directive ng-repeat="foo in foos" foo="foo" my-index="{{$index}}"/>

Error message:

Error: [$parse:syntax] Syntax Error: Token '$index' is unexpected, expecting [:] at column 3 of the expression [{{$index}}] starting at [$index}}].

Here's the directive:

app.directive('myDirective', function() {
    return {
        restrict: 'E',
        scope: { foo: '=', myIndex: '=' },
        templateUrl: 'directives/myDirective.html'
    };
});

This only appears to be an issue with custom directives. If I try this:

<div ng-repeat="foo in foos" style="padding: {{$index}}px;">
    index == {{$index}}
</div>
like image 618
Steve Avatar asked Feb 14 '23 15:02

Steve


1 Answers

Since you are using = to declare your isolated scope property, Angular is expecting a property that is not interpolated:

In order to inject the $index value as the interpolated value change to @:

scope: { foo: '=', myIndex: '@' },

And then use:

<my-directive ng-repeat="foo in foos" foo="foo" my-index="{{$index}}"/>
like image 160
Davin Tryon Avatar answered Feb 16 '23 04:02

Davin Tryon