angularJS中directive与directive 之间的通信

时间:2023-03-08 23:03:08
angularJS中directive与directive 之间的通信

上一篇讲了directive与controller之间的通信;但是我们directive与directive之间的通信呢?

当我们两个directive嵌套使用的时候怎么保证子directive不会被父directive替换覆盖;及当子directive需要用到父directive中controller某个变量或者方法的时候

怎么实现两个directive之间的通信的。

这里主要讲directive的两个属性:

1.transclude

2.require

html

 <!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>angular-directive3</title>
<script src="js/angularjs1.4/angular-1.4.6.mini.js"></script>
<style type="text/css">
#id1 {
width: 200px;
height: 100px;
border: 1px solid #005599;
}
#id2 {
width: 100px;
height: 50px;
margin: 5px;
border: 1px dotted #cccccc;
}
</style>
</head>
<body ng-app="demoDrt"> <deep-drt forid="id1">
<inner-drt forinnerid="id2"></inner-drt>
</deep-drt> </body>
</html>

js

 var demoDrt = angular.module('demoDrt', []);
demoDrt.directive('deepDrt', function() {
return {
restrict:'AE',
replace:true,
scope : {
forid : '@'
},
//加上transclude属性true之后在template中结合ng-transclude指令就不会替换子directive,
// 如果嵌套有自定义指令而没加transclude属性的话子directive会被父directive的template替换掉
transclude:true,
//如果有子directive要使用父directive中controller的值的话变量和函数的定义则要使用this来绑定,$scope绑定的话只会在当前作用域生效
controller:['$scope', function($scope) {
//这个this输出的其实就是controller对象
this.name = 'angular';
this.version = '1.4.6';
}],
//template 上结合ng-transclude使用,如果ng-transclude放在template的父级的话,
// 那么template里面的值会被子directive覆盖,所以我们要用一个dom并加上ng-transclude来在外层包裹子directive。
template:'<div id="{{forid}}">deepDrt<div ng-transclude></div></div>'
};
}); demoDrt.directive('innerDrt', function() {
return {
restrict:"AE",
replace:true,
//require主要作用是寻找父directive,'^'表示向上寻找,后面加上父directive的名字,'?'表示如果找不到的话则不会报错,
// 一般'^?'两个结合使用当找不到父directive的时候angular不会报错
//结合了require 则在子directive的link属性中加上reController,则可以获取父directive中controller的变量和方法
require: '^?deepDrt',
scope : {
forinnerid : '@'
},
link : function(scope, element, attr, reController) {
console.log(scope);
console.log(attr);
//reController得到了父controller中绑定的变量和函数
element.bind('click', function(e) {
console.log(e.target);
e.target.innerText = reController.name + '-' + reController.version;
});
},
template : '<div id="{{forinnerid}}">innerDrt</div>'
}
});

directive生成页面结构

angularJS中directive与directive 之间的通信

通过transclude:true同时在template中结合ng-transclude指令我们能把子directive嵌套在父directive中;而我在注释中也提到了,如果ng-transclude外没有一个dom包裹

子directive的话那字directive也是会被父directive的template替换的。

在子directive中require:'^?deepDrt';具体含义在注释中已经说明。值得注意的是父directive中的controller中定义的变量如果要给子directive使用的话要用this来绑定变量或者方法,this指的就是controller这个对象。子directive中reController得到的就是这个controller对象,从而得到父directive中this定义的变量和属性。

关于angularJS directive之间的通信就这么多;不对之处希望大家指正。谢谢!