2014-12-03 23 views
2

我使用引導彈出模態窗口,並試圖$發射和事件,但由於某種原因,主頁面沒有檢測到事件。這是一個非常簡單的設置,但我不明白爲什麼。從我看到Batarang時可以看出,彈出窗口是主應用程序範圍的子範圍,所以我認爲它會起作用,但它不起作用。在這個簡單的應用程序中,當您在彈出窗口中按下「確定」時,它應該在父範圍中設置一個值。這裏有一個plunker:

http://plnkr.co/edit/F2W1LaWSsqinaFpiISAr?p=preview

//Here's code where $emit is called in the child (Factory): 
var modalInstance = $modal.open({ 
       templateUrl: 'popupMyWindow.html', 
       pScope: parentScope, 
       controller: 
        function($scope, $modalInstance){ 
         $scope.ok = function() { 
          $scope.$emit('ModalSelect', 'hello world'); 
          $modalInstance.close(null); 
         } 
        }, 

//Here's where $on is called in the main controller: 
$scope.$on('ModalSelect', function (event, selected) { 
      console.log('ModalSelect called successfully'); 
      $scope.selectedValue = selected; 
     }); 

謝謝!

回答

3

我不確定將$scope傳遞給服務是個好主意。 $scope與放置在視圖中的位置非常相關,因此您是否可以真正知道您應該使用$emit還是$broadcast?另外,當您通過$scope時,單元測試更加困難。相反,傳遞一個回調函數。

這就是說,你正在調用$emit$modal指令的作用域,它可能是一個孤立的作用域(我不知道該指令是如何定義的),所以它永遠不會到達父級。

所以,你可以這樣做:

parentScope.$emit('ModalSelect', 'hello world'); 

或者,你可以使用$rootScope

$scope.$root.$broadcast('ModalSelect', 'hello world'); 
+0

謝謝,使用廣播從rootscope的伎倆 – Rob 2014-12-03 04:57:58

+0

然而,這是不好的做法。首先,性能:root會將$發送給應用程序中的所有子範圍,無論它們是否正在偵聽。其次,你創建一個依賴到rootScope,從而降低可重用性(請參閱:http://stackoverflow.com/questions/24830679/why-we-use-rootscope-broadcast-in-angularjs) – SKuijers 2015-03-18 10:08:13

+0

準確地說,'$ emit'氣泡建立分級鏈,'$ broadcast' - 向下。所以,root會將'$ emit'只發送給'$ rootScope。$ on'監聽器。但即使使用'$ broadcast' - 性能問題已得到解決 - [請參閱此答案](http://stackoverflow.com/a/19498009/968155) - 只有實際的聽衆纔會收到通知。 – 2015-03-18 14:07:50

相關問題