how to communicate from one directive to another directive

落爺英雄遲暮 提交于 2019-12-23 07:01:28

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!