讲述angularjs创建指令replace,transclude域的用法
angularjs的指令创建有四种形式,比如创建的指令hello:
(1)页面标签的形式E:
<hello>
<div>angularjs创建指令</div>
<div>replace的用法</div>
</hello>
(2)标签属性的形式A(angularjs默认的):<div hello></div>
(3)标签样式类的形式C:<div class="hello"></div>
(4)页面注释的形式M: <!-- directive:hello -->(注释号前后有个空格)
指令的创建代码:
myApp.directive('hello',function(){
return {
restrict:'ACEM',
template:'<div>hello everyone!</div>',
//transclude:false
replace:false
}
});【一】如果replace设置为false,最终页面展现的html结果如下:
C: <div class="hello"><div>hello everyone!</div></div>
A: <div hello=""><div>hello everyone!</div></div>
E: <hello><div>hello everyone!</div></hello>
M: <!-- directive:hello -->(没有效果,无效的)【二】如果replace设置为true,最终页面展现的html结果如下: C:<div class="hello">hello everyone!</div>
A:<div hello="">hello everyone!</div>
E:<div>hello everyone!</div>
M:<div hello="">hello everyone!</div> (有效)使用replace有个什么缺点呢,比如我要把文章开头指令hello下的<div>angularjs创建指令</div> <div>replace的用法</div>要显示在页面上,replace是办不到的,这个可以用transclude域的设置来解决:
myApp.directive('hello',function(){
return {
restrict:'ACEM',
template:'<div>hello everyone!<span ng-transclude></span></div>',
transclude:true
}
});这样就可以把指令内的DOM标签展现出来:
C:<div class="hello"><div>hello everyone!<span ng-transclude=""><span class="ng-scope">样式类</span></span></div></div>
A:<div hello=""><div>hello everyone!<span ng-transclude=""><span class="ng-scope">属性</span></span></div></div>
E:<hello><div>hello everyone!<span ng-transclude="">
<div class="ng-scope">angularjs创建指令</div>
<div class="ng-scope">replace的用法</div>
</span></div></hello>
M:<!-- directive:hello -->
参考:http://stackoverflow.com/questions/15285635/how-to-use-replace-of-directive-definition
本文详细介绍了AngularJS中创建指令的方法,包括replace与transclude域的使用技巧。通过具体示例展示了不同配置下指令的行为变化,帮助开发者更好地理解和应用AngularJS指令。
165

被折叠的 条评论
为什么被折叠?



