2014-03-02 35 views
4

在AngularJS,失败与错误:

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

错误消息:

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

这里的指令:

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

这似乎只是自定义指令的问题。如果我试试这个:

<div ng-repeat="foo in foos" style="padding: {{$index}}px;"> 
    index == {{$index}} 
</div> 

回答

8

由于您使用=来声明孤立scope属性,角期待未插的属性:

为了注入$index值作为插值值更改为@

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

然后用:

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

如果我这样做,它只是获取字符串'“$ index”'(不含引号)而不是'$ index'的值。如何让Angular期望一个插入的属性? –

+1

将'='更改为'@'。这是一个字面的内插值。 –

+0

谢谢,这工作。我注意到你用这个更新了你的答案,但是应该注意的是,用'myIndex:'=''和'my-index =“$ index”',字符串'$ index'被传递,所以第一部分你的答案没有帮助。 –