一个Demo就懂的Angular之directive

时间:2022-01-24 05:44:09
 <body>
<div ng-controller="myCtrl">
<hello-word></hello-word>
</div> <script type="text/javascript">
angular.module('app',[])
.directive('hello-word',function($document){
return {
/***
'E':<hello-word></hello-word>
'A': <div hello-word ></div>
'C': <div class="hello-word: exp;"></div> Class 类名
'M': <!-- directive: hello-word exp --> Comment 注释
*/
restrict: 'E',
// templateUrl: 代表一个路径下的html片段
template: '<div>hello word!!!</div>',
//替换掉原标签
replace: true,
/**
对特定的元素注册事件。需要用到scope参数来实现dom元素的一些行为
function link(scope, element, attrs, controller) { ... }
在link阶段要执行的函数,这个属性只有当compile属性没有设置时才生效
常用参数为scope,element和attrs,分别是当前元素所在的scope,dom元素和元素上的属性们,其它的以后细说
directive基本上都会有此函数,可以注册事件,并与scope相绑 */
link: function(scope, element, attrs){
angular.element(element).bind('click',function(){
alert('hello word!!!!');
})
},
/**
想在dom渲染前对它进行变形,并且不需要scope参数
想在所有相同directive里共享某些方法,这时应该定义在compile里,性能会比较好
返回值就是link的function,这时就是共同使用的时候
*/
compile: function(){ }
}
})
.controller('myCtrl',function($scope,$location){ });
</script>
</body>