angular.module('docsTransclusionExample', []).controller('Controller', ['$scope', function($scope) { $scope.name = 'Tobias';}]).directive('myDialog', function() { return { restrict: 'E', transclude: true, scope: {}, templateUrl: 'my-dialog.html', link: function (scope, element) { scope.name = 'Jeff'; } };});這個在官網上的directive代碼,link函數起到的什么作用,解釋有點費解,然后其中有三個參數scope:is an Angular scope object.element: is the jqLite-wrapped element that this directive matches.attrs: is a hash object with key-value pairs of normalized attribute names and their corresponding attribute values.這個用法是怎樣的,scope好像就是return中得scope屬性。。
2 回答

至尊寶的傳說
TA貢獻1789條經驗 獲得超10個贊
首先我們先來聊聊你列出的directive
中的幾個屬性:
restrict
E: 表示該directive
僅能以element方式使用,即:<my-dialog></my-dialog>
A: 表示該directive
僅能以attribute方式使用,即:<div my-dialog></div>
EA: 表示該directive
既能以element方式使用,也能以attribute方式使用transclude
你的directive
可能接受頁面上的其他html內容時才會用到,建議你先去掉該參數。有些高階了。scope
當你寫上該屬性時,就表示這個directive
不會從它的controller
里繼承$scope
對象,而是會重新創建一個。templateUrl
你的directive
里的html
內容link
可以簡單理解為,當directive
被angular 編譯后,執行該方法
這里你說的沒錯,link
中的第一個參數scope
基本上就是你說的上面寫的那個scope
。
element
簡單說就是$('my-dialog')
attrs
是個map,內容是你這個directive
上的所有屬性,例如:你在頁面上如果這樣寫了directive
:
<my-dialog type="modal" animation="fade"></my-dialog>
那attrs
就是:
{
type: 'modal',
animation: 'fade'
}
- 2 回答
- 0 關注
- 510 瀏覽
添加回答
舉報
0/150
提交
取消