轉自:http://segmentfault.com/q/1010000002400734
官方API:http://docs.angularjs.cn/api/ng/service/$compile
一個民間詳細介紹:http://blog.51yip.com/jsjquery/1607.html
問:
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'; } }; });
答:
1.restrict
E: 表示該directive僅能以element方式使用,即:<my-dialog></my-dialog>
A: 表示該directive僅能以attribute方式使用,即:<div my-dialog></div>
EA: 表示該directive既能以element方式使用,也能以attribute方式使用
2.transclude
你的directive可能接受頁面上的其他html內容時才會用到,建議你先去掉該參數。有些高階了。
3.scope
當你寫上該屬性時,就表示這個directive不會從它的controller里繼承$scope對象,而是會重新創建一個。
4.templateUrl
你的directive里的html內容
5.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' }