AngularJS自定义指令
Transclue:当元素标签需要嵌套时使用,与ng-transclude结合使用。默认值为false,不能使用嵌套,true表示可以使用嵌套。在哪个标记上使用ng-transclude嵌套在哪个标记中。
代码示例:(替换hello和hi标签,并在div中嵌套span标签)
脚本类型=' text/JavaScript ' var m=angular . module(' myApp ',[]);m.directive('hello ',function(){ return { restrict : ' E ',replace:true,transclude:true,template : ' div hello angular h1 ng-transclude/h1/div ' };});m . direction(' hi ',function(){ return { restrict : ' E ',replace:true,template : ' spanhi angular/span ' };});m.controller('Aaa ',['$scope ',function($ scope){ $ scope . name=' hello ';}]);/脚本正文ng-controller=' AAA ' hello hi/hi/hello/正文页面结果显示:
自定义指令中控制器和链接的区别:
链接是指DOM操作,操作也是针对当前标签的
控制器是一个可多次调用的数据共享。一些方法数据也可以在指令相互作用时设置,也可以在其他选项卡中调用
require:从外部引入数据,参数是引入指令,需要在引入指令的主体上。
:表示引入的指令是引入指令的父指令
》?兼容性错误
代码示例:
脚本类型=' text/JavaScript ' var m=angular . module(' myApp ',[]);m.directive('hello ',function(){ return { restrict : ' E ',replace:true,transclude:true,controller : function($ scope){/$ scope . name=' miov ';此标签中只能使用this.name=' miaov//可以在其他标签中调用}、template : ' div hello angular h1 ng-trans clude/h1/div ' };});m.directive('hi ',function(){ return { restrict : ' E ',replace:true,require: '?Hello ',//指令是从外部导入的,参数是导入的标签link:function ($ scope,element,attr,re controller){ console . log(re controller . name);},template : ' span hi angular/span ' };});m.controller('Aaa ',['$scope ',function($ scope){ $ scope . name=' hello ';}]);/脚本正文ng-controller=' AAA ' hello hi/hi/hello/正文页面结果显示:
以上就是本文的全部内容。希望对大家的学习有帮助,支持我们。