2015-10-01 47 views
0

我有一個ng-repeat創建多個指令,每個指令都有一個隔離範圍。我希望能夠調用每個指令調用函數的單個函數,以便在每個隔離範圍上重置一個變量。無論如何我無法做到這一點?我意識到這可能不是最佳做法,但我現在只需要一個解決方案。更新多個指令的隔離範圍

+0

發佈您的代碼,並告訴我們你已經嘗試什麼都。 –

回答

0

一種方法是提供回調指令(即scope: { xxx: '&' }),它將執行一些功能。可能是:

<the-directive callback="ctrl.command(action, argument)" /> 

而且該指令的樣子:

app.directive('theDirective', function() { 
    return { 
     ... 
     scope: { 
      callback: '&', 
      ... 
     }, 
     controller: ['$scope', function($scope) { 
      this.resetTheVariable = function() { 
       // DO WHAT YOU WANT HERE 
      }; 

      $scope.callback({ action: 'register', argument: this }); 

      $scope.$on('$destroy', function() { 
       scope.callback({ action: 'deregister', argument: this }); 
      }); 
     }] 
    }; 
}) 

現在控制器調用該指令將如下所示:

function TheController() { 
    var registeredDirectives = []; 

    this.command = function(action, argument) { 
     switch(action) { 
      case 'register': 
       registeredDirectives.push(argument); 
       break; 
      case 'deregister': 
       var index = registeredDirectives.indexOf(argument); 
       if(index >= 0) { 
        registeredDirectives.splice(index, 1); 
       } 
       break; 
     } 
    }; 

    this.resetAll = function() { 
     registeredDirectives.forEach(function(registeredDirectiveController) { 
      registeredDirectiveController.resetTheVariable(); 
     }); 
    }; 
} 
1

,我在一個類似的靜脈使用另一種方法是angulars事件系統。

我正在創建一個小部件的儀表板。我的小部件是一個包含在ng-repeat中的指令。

我在我的控制器中發出事件$scope.$broadcast然後在我的指令中聽取$scope.$on。我使用ng-repeat$index能夠定位特定的小部件。

簡單的例子小提琴:http://jsfiddle.net/adyjm9g4/

編輯:忘了提,你也可以傳遞數據:http://jsfiddle.net/adyjm9g4/1/

+0

不錯的優雅的解決方案,謝謝! :) – colouredFunk