2014-07-16 33 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

相關問題