【AngularJS】—— 8 自定义指令

AngularJS支持用户自定义标签属性,在不须要使用DOM节点操做的状况下,添加自定义的内容。javascript

前面提到AngularJS的四大特性:html

  1 MVCjava

  2 模块化app

  3 指令框架

  4 双向数据绑定模块化

下面将会介绍以下的内容:函数

  1 如何自定义指令ui

  2 自定义指令的使用spa

  3 自定义指令的内嵌使用rest

  如何自定义指令:

  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:是否支持内嵌

  如何使用指令:

  上面提到了标签的四种使用方法,即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里面声明对应的字母。

 

  指令的内嵌使用:

  由于标签内部能够嵌套其余的标签,所以想要在自定义标签中嵌套其余的元素标签,则须要:

  1 使用transclude属性,设置为true。

  2 并使用ng-transclude属性,定义内部嵌套的位置。

  代码以下:

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

 

  所有代码

<!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>

  运行结果

相关文章
相关标签/搜索