2014-07-16 94 views
-1

我有两个指令,一个是ng-grid,另一个是分页,当我在一个指令中点击页码时,ng-grid指令应该根据这个改变,我可以有什么想法在那。如何沟通从一个指令到另一个指令

+1

你能为你的问题添加一些代码吗? – maurycy

+1

根据您的具体情况,使用'$ scope。$ broadcast','$ scope。$ emit'或'$ rootScope。$ broadcast'。 https://docs.angularjs.org/api/ng/type/$rootScope.Scope – domakas

回答

0

有很多方法来实现它: 例如:

首先解决

可以指令之间共享数据:

<directive-one attribute="value" other-attribute="value2" shared-variable="yourData"> 
<directive-two shared-variable="yourData"> 

并设置$watch后第一个指令内值

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/

+1

使用'。$ parent'坏..真的很差... – PSL

+0

@PSL好吧,我正在改变它;) – akn

相关问题