Link&Compile

compile 和 link
compile函数的作用是对指令的模板进行转换
link作用是在模型和视图之间建立关联,包括在元素上注册事件监听。
scope在链接阶段才会被绑定到元素上,因此compile阶段操作scope会报错。
对于同一指令的多个实例,compile只会执行一次,而link对于指令的每一个实例都会执行一次
一般情况下,我们只要编写link函数就够了
请注意,如果你编写自定义的compile函数,自定义的link函数无效,因为compile函数应该返回一个link函数供后续调用。
link 主要对元素或者是scope进行事件的绑定作用。
index.html

<!DOCTYPE html>
<html ng-app="app">
<head>
    <title>demo</title>
</head>
<body>
   <hello></hello>
</body>
<script src="./angular/angular.js"></script>
<script src="./js/index.js"></script>
</html>

index.js

var app = angular.module('app',[])
app.directive('hello',function(){
    return{
        restrict:'E',
        template:'<div>Hi ereryone</div>',
        replace:'true',
        link:function(scope,el,attrs,controller){//scope element attribute controller
            //link主要对元素 或scope绑定事件
            //console.log('hello link...')
            el.on('mouseenter',function(){
               console.log('mouse enter output...')
            })
        }
    }
})

《Link&Compile》

compile
index.html

<!DOCTYPE html>
<html ng-app="app">
<head>
    <title>demo</title>
</head>
<body>
   <div autohello='5'>
     <p>hello michael</p>
   </div>
</body>
<script src="./angular/angular.js"></script>
<script src="./js/index.js"></script>
</html>

index.js

var app = angular.module('app',[])
app.directive('autohello',function(){
    return{
        restrict:'A',
        //只能当作attribute属性来使用
        compile: function(el,attrs,transclude){
            //对标签元素变换 transclude
            console.log('command starts to compile...')
            var templ = el.children().clone()//拿到元素的孩子节点,然后克农
            console.log(templ)//p标签
            for(var i = 0;i<attrs.autohello-1;i++){//从0开始,所以减1
                el.append(templ.clone())//获得5个
            }
            return function(scope,el,attrs,controller){//函数闭包,return link函数
                console.log('command connecting...')
            }
        }
        
    }
})

《Link&Compile》
注意,如果同时有compile和link,link函数不会执行

var app = angular.module('app',[])
app.directive('autohello',function(){
    return{
        restrict:'A',
        //只能当作attribute属性来使用
        compile: function(el,attrs,transclude){//没有scope,如果操作scope报错
            //对标签元素变换 transclude
            console.log('command starts to compile...')
            var templ = el.children().clone()//拿到元素的孩子节点,然后克农
            console.log(templ)//p标签
            for(var i = 0;i<attrs.autohello-1;i++){//从0开始,所以减1
                el.append(templ.clone())//获得5个
            }
            return function(scope,el,attrs,controller){//函数闭包,return link函数
                console.log('command connecting...')
            }
        },
        link:function(){//这时的link函数不会被执行到,要么有link,要么有compile,两者不可能同时存在
            console.log('self made link ouput...')
        }
        
    }
})
    原文作者:MichaelDuan
    原文地址: https://segmentfault.com/a/1190000003785844
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞