angular自定义指令详解

在运用angularjs的时候,运用自定义指令可以写一些组件,非常方便。这里给大家分享一些关于angular自定义指令的知识。

1. 定义

对于指令,可以把它简单的理解成在特定DOM元素上运行的函数,指令可以扩展这个元素 的功能。

2.定义指令的方法:

angular.module('myApp', []) 
.directive('myDirective', function ($timeout, UserDefinedService) { 
    // 指令定义放在这里 
}); 

第一个参数,指令的名字myDirective 用来在视图中引用特定的指令。
第二个参数是一个函数,这个函数返回一个对象,$compile服务利用这个方法返回的对 象,在DOM调用指令时来构造指令的行为。

3.指令设置的选项

angular.module('myApp', []) 
.directive('myDirective', function() { 
    return { 
        restrict: String, 
        priority: Number, 
        terminal: Boolean, 
        template: String or Template Function: 
            function(tElement, tAttrs) (...}, 
        templateUrl: String, 
        replace: Boolean or String, 
        scope: Boolean or Object, 
        transclude: Boolean, 
        controller: String or  
        function(scope, element, attrs, transclude, otherInjectables) { ... }, 
        controllerAs: String, 
        require: String, 
        link: function(scope, iElement, iAttrs) { ... }, 
        compile: // 返回一个对象或连接函数,如下所示: 
            function(tElement, tAttrs, transclude) { 
                return { 
                    pre: function(scope, iElement, iAttrs, controller) { ... }, 
                    post: function(scope, iElement, iAttrs, controller) { ... } 
                } 
                // 或者 
                return function postLink(...) { ... } 
           } 
    }; }); 
  1. restrict 指令在DOM中可以何种形式被引用或声明

    可选值如下: ( 可组合使用 )

    E(元素) <my-directive></my-directive>
    A(属性,默认值) <div my-directive=”expression”></div>
    C(类名) <div class=”my-directive:expression;”></div>
    M(注释) <–directive:my-directive expression–>

  2. priority 优先级 用来表示指令使用的优先顺序
    如果一个元素上具有两个优先级相同的指令,声明在前面的那个会被优先调用。如果其中一 个的优先级更高,则不管声明的顺序如何都会被优先调用:具有更高优先级的指令总是优先运行。

  3. terminal 用来告诉AngularJS停止运行当前元素上比本指令优先级低的指令。但同当前指令 优先级相同的指令还是会被执行。

    <div ng-app="myApp" ng-controller="myCtr">
    <!--此处在div上使用了两个自定义指令,作为属性存在,但directiveOne优先级高,而且设置了terminal属性,所以directiveSec指令并不会执行-->
       <div directive-Sec directive-One>
        这是自定义指令
       </div>    
    </div>
    var myCtr=["$scope",function($scope){}]
    var app=angular.module("myApp",[]);
    app.controller("myCtr",myCtr);
    app.directive("directiveOne",function(){
    return {
        restrict: "ECMA", 
        priority: 2, 
        terminal: true, 
        template:function(tElement, tAttrs){
            tElement[0].style.fontSize="18px"; //设置字体
        }
    }
    });
    app.directive("directiveSec",function(){
    return {
        restrict: "ECMA", 
        priority: 1, 
        template:function(tElement, tAttrs){
            tElement[0].style.color="red"; //设置颜色
        }
    }
    });
  4. template
    用来表示模板,可以是一段字符串,如“<h1>这是自定义指令</h2>”,也可以是一个函数,可以参考上面的例子

    template:function(tElement, tAttrs){
    //tElement表示当前元素,是一个数组,tAttrs表示该元素的属性,是一个对象
       tElement[0].style.color="red"; //设置颜色
    }
    
  5. templateUrl 用来表示模板,与上面的template功能相似,但表示路径,可以是外部HTML文件路径的字符串也可以是一个可以接受两个参数的函数,参数为tElement和tAttrs,并返回一个外部HTML文件 路径的字符串。

  6. replace 默认为false,模板会被当作子元素插入到调用此指令的元素内部,为true,则直接替换此元素

    <div some-directive></div> 
    .directive('someDirective', function() { 
    return { 
        template: '<div>some stuff here<div>' 
    }; }); 
    <!-- 调用指令之后的结果如下(这是默认replace为false时的情况):  -->
    <div some-directive> 
    <div>some stuff here<div> 
    </div> 
    
    
    <!-- 如果replace被设置为了true:  -->
    .directive('someDirective', function() { 
    return { 
        replace: true // 修饰过 
        template: '<div>some stuff here<div>' 
    }; }); 
    <!-- 指令调用后的结果将是:  -->
    <div>some stuff here<div> 
  7. scope

    (1)当scope设置为true时,会从父作用域继承并创建一个新的作用域对象。
    (2) 默认为false,并不会创建新的作用域对象,直接使用父scope。
    (3)设置为{},表示隔离作用域,指令的 模板就无法访问外部作用域了
    
    var myCtr=["$scope",function($scope){
        $scope.name="father controller!!"
    }]
    var app=angular.module("myApp",[]);
    app.controller("myCtr",myCtr);
    app.directive("directiveOne",function(){
        return {
            restrict:"ECMA",
            template: '<div>这是自定义指令{{name}}<div>',
            scope:{},
            controller:function($scope){
                console.log($scope.name);//打印出来为undefined,因为无法访问尾部作用域了
            }
        }
    });
    当然,AngularJS提供了几种方法能够将指令内部的隔离作用域,同指令外部的作用域进行数据绑定。
    (a)@ (or @attr) 单向绑定,外部scope能够影响内部scope,但反过来不成立
          <body>
        <div ng-app="myApp" ng-controller="myCtr">
            <input type="" name="" ng-model="value">
            <!-- 注意此处的svalue要写成s-Value,不然没效果-->
              <directive-One s-Value="{{value}}">
                  
              </directive-One>
        </div>
    <!--  -->
    </body>
    <script type="text/javascript">
        var myCtr=["$scope",function($scope){
            $scope.value="";
        }]
        var app=angular.module("myApp",[]);
        app.controller("myCtr",myCtr);
        app.directive("directiveOne",function(){
            return {
                restrict:"ECMA",
                template: '<div>这是自定义指令<input type="" name="" ng-model="sValue">{{sValue}}<div>',
                scope:{
                    sValue:"@"
                },
                controller:function($scope){
                    $scope.sValue="";
                    console.log($scope.sValue);
                }
            }
        });
    
    </script>
    (b)= (or =attr)  双向绑定,外部scope和内部scope的model能够相互改变
        <body>
            <div ng-app="myApp" ng-controller="myCtr">
                <input type="" name="" ng-model="value">
                <!-- = 前面的value表示自定义指令自己的属性名,后面的value表示父作用域的value -->
                  <directive-One value="value">
                      
                  </directive-One>
            </div>
        
        </body>
        <script type="text/javascript">
            var myCtr=["$scope",function($scope){
                $scope.value="1";
            }]
            var app=angular.module("myApp",[]);
            app.controller("myCtr",myCtr);
            app.directive("directiveOne",function(){
                return {
                    restrict:"ECMA",
                    template: '<div>这是自定义指令<input type="" name="" ng-model="value">{{value}}<div>',
                    scope:{
                        value:"="
                    },
                    controller:function($scope){
                        $scope.value="";
                        console.log($scope.value);
                    }
                }
            });
        
        </script>
        ![图片描述][1]
        上面的输入框输入,下面会变,下面的输入框输入上面的也会变
    
        (c)& (or &attr)  把内部scope的函数的返回值和外部scope的任何属性绑定起来
    
  8. controller
    controller参数可以是一个字符串或一个函数。当设置为字符串时,会以字符串的值为名字, 来查找注册在应用中的控制器的构造函数.当为函数时,可以像平时写控制器那样写,可以将任意可以被注入的AngularJS服务传递给控制器

  9. controllerAs(字符串)
    controllerAs参数用来设置控制器的别名,可以以此为名来发布控制器,并且作用域可以访 问controllerAs。这样就可以在视图中引用控制器,甚至无需注入$scope。

  10. require
    require参数可以被设置为字符串或数组,字符串代表另外一个指令的名字。require会将控 制器注入到其值所指定的指令中,并作为当前指令的链接函数的第四个参数。

字符串或数组元素的值是会在当前指令的作用域中使用的指令名称。

    原文作者:北城以南
    原文地址: https://segmentfault.com/a/1190000009820031
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞