2014-03-02 63 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'被傳遞,所以第一部分你的答案沒有幫助。 –