在angularjs中的directive的scope,分別有以下3種設定方式:
- = or =attr : 指定需要連結的model名稱,會與parent scope的model互相綁定。
- @ or @attr : 依照屬性的value傳入,來設定directive的scope值。
- & or &attr : 將預設的function,委託給其他event呼叫。
只要directive有設定scope對應的值,或者設定scope:true
,則directive將會自行建立一個新的scope。
使用 & 和 @ 屬性來設定scope
定義一個alert屬性:
1 | <div alert on-enter="$window.alert('Hello world')" message="Say hello world!"></div> |
其中message
屬性為alert呈現的訊息,on-enter
則會在按鈕被點擊即時會觸發。
實作一個alert directive:
1 | app.directive( "alert", function(){ |
alert的scope
將會取得onEnter
和message
的屬性,分別去對照template的ng-click="onEnter()"
和ng-bind="message"
。
Demo
完整的範例,請參考jsfiddle上的code。