源码网商城,靠谱的源码在线交易网站 我的订单 购物车 帮助

源码网商城

AngularJS 自定义指令详解及实例代码

  • 时间:2020-06-23 07:48 编辑: 来源: 阅读:
  • 扫一扫,手机访问
摘要:AngularJS 自定义指令详解及实例代码
AngularJS支持用户自定义标签属性,在不需要使用DOM节点操作的情况下,添加自定义的内容。 前面提到AngularJS的四大特性:   1 MVC   2 模块化   3 指令   4 双向数据绑定 下面将会介绍如下的内容:   1 如何自定义指令   2 自定义指令的使用   3 自定义指令的内嵌使用 [b]  如何自定义指令:[/b]   Angular是基于模块的框架,因此上来肯定要创建一个自己的模块: var myAppModule = angular.module("myApp",[]);   然后在此模块基础上创建指令directive      
 myAppModule.directive("xingoo",function(){
    return{
     restrict:'AECM',
     template:'<div>hello my directive</div>',
     repalce:true
    }
   });
  其中,xingoo是我们自定义标签的名字,后面跟着它的方法函数。   函数return了一个键值对组合,其中定义了标签的使用方法、属性等等内容。   那么看看它都定义了哪些内容吧:   1 restrict:定义了标签的使用方法,一共四种,分别是AECM   2 template:定义标签的模板。里面是用于替换自定义标签的字符串   3 repalce:是否支持替换   4 transclude:是否支持内嵌 [b]  如何使用指令:[/b]   上面提到了标签的四种使用方法,即AECM。   A attribute属性:当做属性来使用 <div xingoo></div>   E element元素:当做标签元素来使用 <xingoo></xingoo>   C class类:当做CSS样式来使用 <div class="xingoo"></div>   M comments注释:当做注释使用(这种方式在1.2版本下亲测不可用!) <!-- directive:xingoo --> <div></div>   一般来说推荐,当做属性和元素来使用。   当想要在现有的html标签上扩展属性时,采用属性的方式。   当想要自定义标签时,采用标签的形式。   想要使用那种方式,必须要在定义directive中的restrict里面声明对应的字母。  [b]  指令的内嵌使用: [/b]   因为标签内部可以嵌套其他的标签,因此想要在自定义标签中嵌套其他的元素标签,则需要:   1 使用transclude属性,设置为true。   2 并使用ng-transclude属性,定义内部嵌套的位置。   代码如下:      
  myAppModule.directive("test",function(){
    return{
     restrict:'AECM',
     transclude:true,
     template:"<div>haha! <div ng-transclude></div> wuwu!</div>"
    }
   });
 
[b]  全部代码[/b]
<!doctype html>
<html ng-app="myApp">
 <head>
   <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
   <script src="http://apps.bdimg.com/libs/angular.js/1.2.16/angular.min.js"></script>
 </head>
 <body>
  
  <xingoo></xingoo>
  <div xingoo></div>
  <div class="xingoo"></div>
  <!-- directive:xingoo -->
  <div></div>
  <hr>
  <xingoo>3333</xingoo>
  <hr>
  <test>4444</test>


  <script type="text/javascript">
   var myAppModule = angular.module("myApp",[]);

   myAppModule.directive("xingoo",function(){
    return{
     restrict:'AECM',
     template:'<div>hello my directive</div>',
     repalce:true
    }
   });

   myAppModule.directive("test",function(){
    return{
     restrict:'AECM',
     transclude:true,
     template:"<div>haha! <div ng-transclude></div> wuwu!</div>"
    }
   });
  </script>
 </body>
</html>

  运行结果 [img]http://files.jb51.net/file_images/article/201609/2016914155740193.jpg?2016814155755[/img] 以上就是对AngularJS 自定义指令的资料整理,后续继续补充相关资料,谢谢大家对本站的支持!
  • 全部评论(0)
联系客服
客服电话:
400-000-3129
微信版

扫一扫进微信版
返回顶部