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属性。。
首先我们先来聊聊你列出的
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
:那
attrs
就是:{
type: 'modal',
animation: 'fade'
}