zoukankan      html  css  js  c++  java
  • AngularJS---自定义指令

    AngularJS提供了一系列的内置指令,如ng开头的指令,同时AngularJS也允许用户自定义指令。

    目录:

      1.自定义指令

      2.使用自定义指令

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

    自定义指令

    AngularJS中使用directive()方法来自定义指令,directive() 方法可以接受两个参数:

      name(字符):指令的名字,用来在视图中引用特定的指令

      factory_function(函数):这个函数返回一个对象,其中定义了指令的全部行为

    例如:创建一个test指令:

    var app = angular.module('myApp',[]);
        app.directive('hello',function(){
            return {
                restrict:'AECM',
                template:'<div>hello world</div>',
                replace:true
            };
        });

    说明:

    在directive方法的第二个函数参数中,返回了一个对象,字段的意义如下:

    restrice:定义了标签的使用方法,一共四种,分别是AECM

    template:定义标签的模板。里面是用于替换自定义标签的字符串

    repalce:是否替换

    另外还有transclude:标识是否嵌套

    使用自定义指令

    指令在html中的使用有4中方法,分别对应restrice的标签的4个使用方法AECM

    A:属性

    <div hello></div>--------><div>hello world</div>

    E:元素

    <hello></hello>--------><div hello="">hello world</div>

    C:样式(class的值)

    <div class="hello"></div>------><div class="hello">hello world</div>

    M:注释

    <!-- directive:hello ----------->各个版本不一样

    自定义指令的内嵌使用

    app.directive('test',function(){
        return {
            restrict:'AECM',
            template:'<div>hello <div ng-transclude></div> world</div>',
            transclude:true
        };
    });

    说明:自定义指令的内嵌使用需要将transclude字段赋值为true,template中使用ng-transclude来确定内嵌的位置。

    实例代码如下:

    <!DOCTYPE>
    <html ng-app="myApp">
    <head>
         <meta charset="utf-8" />
         <script src="https://code.angularjs.org/1.3.1/angular.min.js"> </script>
    </head>
    <body>
        <div>0</div>
        <hello></hello>
        <div>1</div>
        <div hello></div>
        <div>2</div>
        <div class="hello"></div>
        <div>3</div>
        <!-- directive:hello -->
        <div>4</div>
        <hello>3333</hello>
        <div>5</div>
        <test>4444</test>
        <script type="text/javascript">
            var app = angular.module('myApp',[]);
            app.directive('hello',function(){
                return {
                    restrict:'AECM',
                    template:'<div>hello world</div>',
                    replace:true
                };
            });
            
            app.directive('test',function(){
                return {
                    restrict:'AECM',
                    template:'<div>hello <div ng-transclude></div> world</div>',
                    transclude:true
                };
            });
        </script>
    </body>
    </html>

     

  • 相关阅读:
    ASP.NET MVC 异常捕获
    Jquery 扩展方法
    Spring.NET笔记1
    ASP.NET MVC Ninject 实现依赖注入
    ASP.NET MVC Unity实现依赖注入
    windows service
    反射用法
    抽象工厂核心反射
    (C#)中的DataSet、string、DataTable等对象转换成Json
    .NET批量删除代码前的行号
  • 原文地址:https://www.cnblogs.com/y-yxh/p/5865728.html
Copyright © 2011-2022 走看看