Angular的Directive,以及copmile和link方法


Directive,指令

在Angular中,是指嵌套在HTML模板中的指令,如Angular自带的ng-app ng-controller等,自带指令使用ng-前缀,自定义指令请避免使用。

指令的声明形式

HTML标签元素指令,HTML标签属性指令,Class类指令和HTML注释指令。

其中一般常用的为指令标签和属性标签。

简单的Directive定义

app.directive("myDirective", function() {
  return {
    restrict: "A",
    templateUrl: "context.html",
    replace: true
  }
})
其中,
  • restrict指定指令的声明形式

E表示标签元素指令,如 <my-directive> </my-directive>

A表示标签属性指令,如<div my-directive></div>

Class(C)和注释(M)两种形式请避免使用。

同时支持多种声明形式,可以写为"EA"

如果省略,系统默认为“A”。

<ul><li><span style="font-family: Arial, Helvetica, sans-serif;">templateUrl</span></li></ul>
指令标签内容的模板URL。对于简单的模板,也可以使用template,直接写模板内容。
  • replace

表示指令产生的内容是否会替换整个标签,还是插入到标签的内容。

指令命名规范

指令定义时,需要使用驼峰格式命令,如myDirective。

HTML中引用指令时,需要把驼峰命名进行拆分,可以采用多种方式,如

  1. 冒号:my:directive
  2. 横线:my-directive(推荐)
  3. 下划线:my_directive
  4. x-前缀
  5. data-前缀

推荐使用横线的形式。

指令中的compile和link

以上示例的Directive非常的简单,只是替换一个模板,这样简单的功能完全可以使用ng-include直接嵌入模板的内容。

如果需要给Directive自定义事件或则用程序生成模板,该如何实现呢。这里,就需要用到compile和link函数了。


基于性能的考虑,Angular中,模板的处理过程分为compile和link两个阶段,Directive也会在这两个阶段分别进行处理。

compile阶段:compile阶段主要是对模板内容的处理,可以对模板内容进行修改,如ng-repeat就是在compile阶段执行的。

link阶段:link阶段主要对模板进行数据绑定和事件绑定等操作。

compile阶段

compile阶段会把HTML片段转换为DOM对象,在compile方法中对DOM进行操作。
模仿ng-repeat指令,开发一个my-repeat指令,对子元素重复指定的次数。

先看下compile函数的定义。

function compile(element, attrs, transclude) { ... }
element为指令所在的DOM对象,attrs为元素的属性字典,其他参数暂时未用到,可查看API。

app.directive('myRepeat', function($document) {
  return {
    restrict: 'A',
    compile: function(element, attrs) {
      var template = $(element).children().clone();
      for(var i=0; i<attrs.myRepeat; i++) {
        $(element).append(template.clone());
      }
    }
  }
});

<ul my-repeat="5">
  <li>Hello, my Repeat</li>
</ul>

link阶段

link阶段主要是对元素绑定scope数据和进行事件绑定。

function link(scope, element, attrs, controller) { ... }

scope为模板的作用域数据,其他参数名称自解释。

以一个密码框失去焦点时调用函数进行密码复杂度校验的指令为例。

app.directive('myBlur', function($document) {
  return {
    link: function(scope, element, attrs) {
      $(element).bind('blur', function(e){
         scope.$apply(attrs.myBlur);
      });
    }
  }
})

<input type="password" ng-model="password" my-blur="checkComplex()" />

其中checkComplex为controller中的方法。


在Directive中compile和link函数不能同时出现,如果定义了compile函数,则会忽略link函数。

如果compile后要对数据进行绑定事件,则compile的返回值就定义为link函数。在link阶段,会调用compile的返回值作为link函数。


controller,link,compile有什么不同

Java代码   收藏代码
  1. //directives.js增加exampleDirective  
  2. phonecatDirectives.directive('exampleDirective', function() {  
  3.     return {  
  4.         restrict: 'E',  
  5.         template: '<p>Hello {{number}}!</p>',  
  6.         controller: function($scope, $element){  
  7.             $scope.number = $scope.number + "22222 ";  
  8.         },  
  9.         //controllerAs:'myController',  
  10.         link: function(scope, el, attr) {  
  11.             scope.number = scope.number + "33333 ";  
  12.         },  
  13.         compile: function(element, attributes) {  
  14.             return {  
  15.                 pre: function preLink(scope, element, attributes) {  
  16.                     scope.number = scope.number + "44444 ";  
  17.                 },  
  18.                 post: function postLink(scope, element, attributes) {  
  19.                     scope.number = scope.number + "55555 ";  
  20.                 }  
  21.             };  
  22.         }  
  23.     }  
  24. });  
  25.   
  26. //controller.js添加  
  27. dtControllers.controller('directive2',['$scope',  
  28.     function($scope) {  
  29.         $scope.number = '1111 ';  
  30.     }  
  31. ]);  
  32.   
  33. //html  
  34. <body ng-app="phonecatApp">  
  35.     <div ng-controller="directive2">  
  36.         <example-directive></example-directive>  
  37.     </div>  
  38. </body>  
  运行结果:
Java代码   收藏代码
  1. Hello 1111 22222 44444 55555 !    
  由结果可以看出来,controller先运行,compile后运行,link不运行(link就是compile中的postLink)。 将上例中的compile注释掉运行结果:
Java代码   收藏代码
  1. Hello 1111 22222 33333 !    
  由结果可以看出来,controller先运行,link后运行,link和compile不兼容。compile改变dom,link事件的触发和绑定



在link函数中进行事件绑定

指令里添加事件的方法:

1、在指令的模板里添加angular事件属性,比如添加ng-click属性,然后在指令的link函数中通过scope绑定事件方法。


app.directive('page', function() {
    return {
        restrict: 'E',
        replace: true,
        template: function(tElement, tAttrs) {
            var isClickable = angular.isDefined(tAttrs.isClickable) && eval(tAttrs.isClickable) === true ? true : false;

            var clickAttr = isClickable ? 'ng-click="onHandleClick()"' : '';

            return '<div ' + clickAttr + ' ng-transclude></div>';
        },
        transclude: true,
        link: function(scope, element, attrs) {
            scope.onHandleClick = function() {
                console.log('onHandleClick');
            };
        }
    };
});

摘自: Add ng-click dynamically in directive link function


2、在指令的模板里添加angular事件属性,比如添加ng-click属性,然后在父控制器中通过scope绑定事件方法。
指令作用域中的&
主要作用是传递一个来自父scope的函数,稍后调用。

<!doctype html>
<html ng-app="MyModule">
<head>
<meta charset="utf-">
<link rel="stylesheet" href="../css/bootstrap.css">
</head>
<body>
<div ng-controller="MyCtrl">
<greeting greet="sayHello(name)"></greeting>
<greeting greet="sayHello(name)"></greeting>
<greeting greet="sayHello(name)"></greeting>
</div>
</body>
<script src="../js/angular.js"></script>
<script src="ScopeAnd.js"></script>
</html>
var myModule = angular.module("MyModule", []);
myModule.controller('MyCtrl', ['$scope', function($scope){
$scope.sayHello=function(name){
alert("Hello "+name);
}
}])
myModule.directive("greeting", function() {
return {
restrict:'AE',
scope:{
greet:'&'
},
template:'<input type="text" ng-model="userName" /><br/>'+
'<button class="btn btn-default" ng-click="greet({name:userName})">Greeting</button><br/>'
}
});

摘自: directive和controller通信方法


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值