angularjs教程|angularJS中的子指令的学习笔记

更新时间:2020-01-16    来源:js教程    手机版     字体:

【www.bbyears.com--js教程】

前面有篇文章我已经简单的介绍了angular的指令,我们来看看。


angular有一个强大的功能就是指令,它可以改变页面的DOM,像ng-app、ng-controller、ng-click等都是指令,我们还可以创建自己的指令,如下:





 

    <script src="//cdn.bootcss.com/angular.js/1.3.17/angular.js"></script>

    <script type="text/javascript">

    var app = angular.module('app',[]);

    app.controller('Ctrl',function ($scope,$interval) {});

   app.directive('newEle',function () {

    return {

     link: function($scope,element,attr){

    element.bind('click',function () {

     alert(11)

    })

   },

  template:'

这是指令创建的元素

'     }    })     </script>     

页面的元素

     

效果如下:

 

两种方式都可以绑定指令,直接创建html标签和给标签属性,同时点击新创建的元素可以执行绑定的事件。

值得注意的是:绑定指令的时候不能使用驼峰命名,要使用连接符”-“。


angular里其实可以指令套指令,也就是说在我们创建的指令里面继续添加我们想要的指令,以满足我们复杂的需求,首先上代码:




 
 Document
 
 <script src="http://cdn.bootcss.com/angular.js/1.4.4/angular.js"></script>
 <script>
 angular.module('demo',[])
 .directive('box',function(){
  return{
   controller:function(){
    this.setBigWidth = function(ele){
     ele[0].style.width = '100px';
    }
    this.setBigHeight = function(ele){
     ele[0].style.height = '100px';
    }
    this.setBg = function(ele){
     ele[0].style.background = 'red';
    }
   }
  }
 })
 .directive('bigwidth',function(){
  return{
   require:'box',
   link:function(scope,ele,attr,boxCtrl){
    ele.bind('mouseenter',function(){
     boxCtrl.setBigWidth(ele);
    })
    
   }
  }
 })
 .directive('bigheight',function(){
  return{
   require:'box',
   link:function(scope,ele,attr,boxCtrl){
    ele.bind('mouseenter',function(){
     boxCtrl.setBigHeight(ele);
    })
   }
  }
 })
 .directive('red',function(){
  return{
   require:'box',
   link:function(scope,ele,attr,boxCtrl){
    ele.bind('mouseenter',function(){
     boxCtrl.setBg(ele);
    })
   }
  }
 })
 </script>
 


  
  
  


效果图如下:

 

初始效果是这样:

lingdublog.com/wp-content/uploads/2015/08/20150823212651_26618.jpg"/>

 

鼠标依次放入三个div后的效果是这样:

 

lingdublog.com/wp-content/uploads/2015/08/20150823212720_63828.jpg"/>

 

分析代码,我们把指令box看做是父指令,在它里面有一个controller方法体,controller方法体里面的方法是开放的,可以供引用它的指令调用,我们在里面分别写了三种操作DOM的函数。在下面三个子指令里面,我们首先引用父指令,使用require,然后使用link方法给元素绑定事件,在事件里面我们可以使用父指令里面定义好的函数,注意,link方法的第四个参数就是指向父指令的controller方法体。

最后一点需要注意的是,这应该是angular的一个小坑,在我们命名指令的时候,即使我们html里面使用了驼峰命名法,在这里也一律使用小写,如上面的指令bigWidth,在html中使用的驼峰,在js中使用的是小写

本文来源:http://www.bbyears.com/wangyezhizuo/84567.html

热门标签

更多>>

本类排行