Angular1 Directive开发——基本流程

首先看一个基础示例:

 1 var app = angular.module("myControlModule"); /*作为基础控件,一个module实现一个指令,方便在其它module中单独引用*/
 2   app.directive('myControl', ['$compile', '$controller',
 3     function($compile, $controller) { /*$compile 和 $controller 是本directive依赖的angular基础模块*/
 4       return {
 5         restrict: 'E', // 指令作为元素使用,还可以是A属性、C类、M注释
 6         replace: true,   // 替换现有元素
 7         scope: {  
 8           text: '='
 9         },
10         controller: ['$scope', function(scope){ // 指令控制器
11           /* PS:可增加对外提供的方法 */
12         }],
13         template: function() {
14           return '';  // 模板
15         },
16         compile: function() {  // 编译函数,转换模板DOM;最后返回一个link函数(模板和视图的建立关联,包括事件),因此此时若有link函数将不会生效
17           return {
18             pre或post: _link    /// pre和post的区别将在下面讲解
19           }
20         }
21       }
22       function _link(scope, elment, attsr) {
23          /*实现组件的初始化,事件等*/
24       }
25     }
26   ]);    
  • compile中pre和post

    pre  视图和模型还没有关联,此时适合做一些scope的运算,如果使用了外部组件,需要在这里进行组件初始化

    post  视图和模型已建立关联,此时适合进行Dom操作,增加事件、位置改变等

原文地址:https://www.cnblogs.com/yiyitong/p/6222664.html