2012-10-14 30 views
6

這裏是我的指令:在Angular JS中,我如何從指令屬性注入數據到模板?

app.directive("helloWorld", function() { 
    return { 
    restrict: "E", 
    scope: { 
     name: "bind" 
    }, 
    template: "<div>a {{name}} a</div>" 
    }; 
}); 

下面是我如何使用它:

<hello-world name="John Smith"></hello-world> 

我希望這個頁面是這樣的,當我運行它:

<hello-world> 
    <div>a John Smith a</div> 
</hello-world> 

但對於一些原因,name未注入,實際結果如下:

<hello-world> 
    <div>a {{name}} a</div> 
</hello-world> 

我錯過了什麼?我正在使用Angular JS 1.0.2

回答

14

範圍聲明很奇怪。我不確定關於"bind"聲明 - 也許它是以前版本中的一些。

目前的語法綁定到一個指令的屬性是這樣的:

return { 
    restrict: "E", 
    scope: { 
     name: "@name" 
    }, 
    template: "<div>a {{name}} a</div>" 
}; 

一般來說,@attributeName。看到這裏爲more information on directives

+0

剛剛回答我自己的問題,然後它似乎已經有一個答案:-) https://groups.google.com/forum/?fromgroups=#!topic/angular/tfArd7DuFxs – agibalov

+1

我建議添加更多的信息關於範圍。 「@name」綁定到父範圍內的給定屬性; 「= getName()」綁定到父範圍中的Angular表達式'getName()'的值;和「&doStuff()」將函數綁定到調用時執行給定角度表達式的作用域。 – qualidafial

相關問題