问题
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.
回答1:
There are many ways to achieve it: For example:
First solution
You can share data between directives:
<directive-one attribute="value" other-attribute="value2" shared-variable="yourData">
<directive-two shared-variable="yourData">
And set $watch
inside first directive on that value
scope.$watch('yourData',function(newVal,oldVal){ //your logic called after change });
Second solution
You can use events:
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!');
};
}
}
});
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/
来源:https://stackoverflow.com/questions/24778496/how-to-communicate-from-one-directive-to-another-directive