当前位置: 移动技术网 > IT编程>脚本编程>AngularJs > AngularJS指令与指令之间的交互功能示例

AngularJS指令与指令之间的交互功能示例

2018年05月03日  | 移动技术网IT编程  | 我要评论

本文实例讲述了angularjs指令与指令之间的交互功能。分享给大家供大家参考,具体如下:

前面一篇文章《angularjs指令与控制器之间的交互功能示例》我们了解了指令与控制器之间的交互,接下来看看指令与指令之间是如何进行交互的。

1.首先来了解一下什么是独立scope

为了更好的理解独立scope,我们来看一段代码:

<div ng-controller="mycontroller1">
    <hello></hello>
    <hello></hello>
</div>

var app=angular.module('firstapp',[]);//app模块名
  app.controller('mycontroller1',['$scope',function($scope){
}]);
app.directive('hello',function(){
    return{
      restrict:'e',
      template:"<div><input type='text' ng-  model='username'/>{{username}}",
      replace:true
    }
})

我们定义了一个指令,并在html中调用了两次,我们发现,调用两次的结果为:使用同一个指令构建的scope共享了一个数据,结果如下,我们在一个输入框中输入数据,会改变第二个指令中的输入框

如何解决这个问题呢,我们需要给指令生成独立的scope,每次使用指令时,生成的scope都是独立的,我们只需要如此修改:

app.directive('hello',function(){
    return{
      restrict:'e',
      scope:{},
      template:"<div><input type='text' ng-model='username'/>{{username}}",
      replace:true
    }
})

结果如下:

2.指令与指令之间的交互,指令的继承

(1)首先我们定义了一个父指令,定义的方式如下:

app.directive('father',function(){
    return{
     restrict:'e',
     scope:{},
     controller:function($scope){
      this.mean1=function(){
       console.log('这是第一个方法....');
      };
      this.mean2=function(){
       console.log('这是第二个方法....');
      };
      this.mean3=function(){
       console.log('这是第三个方法....');
      }
     }
    }
});

我们注意到,指令里面也有controller,这里的controller与控制器定义过程中的不同,这里的controller指的是指令的独立scope中定义的一些方法。

(2)定义子指令,子指令中可以使用父指令中scope中的方法:

app.directive('childfirst',function(){
    require:'^father',
    link:function(scope,ele,attr,fatherctrl){
      fatherctrl.mean1();
    }
})

这样通过:

require:'^father'

子指令就可以继承并且使用父指令中,独立scope中的一些方法。此时我们的link函数就可以有第四个参数。

link和controller中方法的区别:

link中的方法是需要执行或者马上要执行的方法。

controller中的方法是希望暴露出来,给外部使用的一些方法。

总结:

指令之间的交互,是通过指令的controller中暴露出来的方法,给外部指令使用。

更多关于angularjs相关内容感兴趣的读者可查看本站专题:《angularjs入门与进阶教程》及《angularjs mvc架构总结

希望本文所述对大家angularjs程序设计有所帮助。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网