6

我正在一個單頁的應用程序,與角和我需要溝通2個不同的指令,基本上沒有父子關係。

在指令A中,我有兩個地方需要從不同的功能廣播相同的事件。在指令B中,爲此寫了一個$聽衆。

現在,我觀察到每當callFirstFunc &它的廣播首次被調用時,監聽器將被調用一次。在隨後的調用中,監聽者被調用兩次,三次等等,它不斷增加。

callFirstFunc在callFirstFunc被執行時調用,所以這個監聽器也被稱爲許多no。在callFirstFunc中廣播監聽者的次數。 那麼,爲什麼聽衆不會只調用一次,爲什麼多次?它每次循環和增加。

指令答:

app.directive("firstDir", function ($rootScope) { 
    return { 
     restrict: 'E', 
     link: function (scope, element, attrs) { 
      // some other code 
      callFirstFunc(); 
      var callFirstFunc = function(){ 
       // some other code 
       $rootScope.$broadcast("someEvent"); 
      } 
      callSecondFunc(); 
      var callSecondFunc = function(){ 
       // some other code 
       $rootScope.$broadcast("someEvent"); 
      } 
     } 
    }; 
}); 

指令B:

app.directive("secondDir", function ($rootScope) { 
     return { 
      restrict: 'E', 
      link: function (scope, element, attrs) { 
       // some other code 
       scope.$on("someEvent", function(){ 
        detectSTuff(); 
       }) 
       function detectStuff(){ 
        // other code 
       }      
      } 
     }; 
    }); 
+0

[AngularJs廣播重複執行的次數太多(可能的重複http://stackoverflow.com/questions/19553598/angularjs- broadcast-repeating-execution-too-many-times) – kinkajou 2017-01-18 01:30:25

回答

1

我想你忘了取消綁定,甚至處理。

你可以像下面 -

var someEventHandle = scope.$on("someEvent", function(){ 
 
        detectSTuff(); 
 
       }); 
 
scope.$on('$destroy', someEventHandle);

+4

Rabi - 我試過了,但它仍然是一樣的。它不止一次收聽並不斷增加。 – whyAto8 2014-11-06 17:55:46