如何从一个指令通信到另一个指令 [英] how to communicate from one directive to another directive
问题描述
我有两个指令,一个用于 ng-grid,另一个用于分页,当我点击一个指令中的页码时,ng-grid 指令应该根据那个进行更改,我对此有何想法.
I have tow directives one is for ng-grid another is for pagination when I click page numbers in one directive ng-grid directive should be changed according to that, can I have any idea on that.
推荐答案
有很多方法可以实现:例如:
There are many ways to achieve it: For example:
第一个解决方案
您可以在指令之间共享数据:
You can share data between directives:
<directive-one attribute="value" other-attribute="value2" shared-variable="yourData">
<directive-two shared-variable="yourData">
并在该值的第一个指令中设置 $watch
And set $watch
inside first directive on that value
scope.$watch('yourData',function(newVal,oldVal){ //your logic called after change });
第二种解决方案
您可以使用事件:
app.directive('first',function(){
return{
restrict: 'E',
template: 'Im first directive!',
scope: true,
link:function(scope,elem,attrs){
scope.$on('event',function(event,args){
alert(args);
});
}
}
});
app.directive('second',function($rootScope){
return{
restrict: 'E',
template: 'Im second directive! <button ng-click="click()">click me!</button>',
scope: true,
link:function(scope,elem,attrs){
scope.click = function(){
$rootScope.$broadcast('event','hello!');
};
}
}
});
事件由$rootScope.$broadcast('event','hello!');
发送.这意味着事件由您的根作用域向下发送到子作用域.http://jsfiddle.net/aartek/fJs69/
Event is sent by $rootScope.$broadcast('event','hello!');
. It means event is sent by your root scope downwards to child scopes. http://jsfiddle.net/aartek/fJs69/
这篇关于如何从一个指令通信到另一个指令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!