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 關注
- 519 瀏覽
添加回答
舉報
0/150
提交
取消
