2015-07-02 81 views
2

我想用角度創建自定義事件。目標是通過服務廣播該事件,並且必須在控制器中捕捉。Angular:服務中的廣播事件

我有我的服務:

function doSomething() { 
     // do something... 
     $rootScope.$broadcast("bced"); 
     $rootScope.$emit("emitted"); 
     console.log('event'); 
} 

和我的控制器:

$rootScope.$on("bced",function(){ 
    console.log("catched"); 
}); 
$rootScope.$on("emitted",function(){ 
    console.log("catched"); 
}); 

$scope.$on("bced",function(){ 
    console.log("catched"); 
}); 
$scope.$on("emitted",function(){ 
    console.log("catched"); 
}); 

但我不能趕上控制器事件。 console.log('event')顯示,但我無法捕捉任何事件。 有人能解釋我該怎麼做嗎? $ rootScope在服務和控制器中正確聲明。

回答

6

結帳工作演示:

var app = angular.module('core', []); 
 
    app.service('SomeService', function($timeout, $rootScope){ 
 
     this.generateEvent = function(){ 
 
      $timeout(function(){ 
 
       $rootScope.$broadcast('event:show', {some: 'data'}); 
 
      }, 3000);  
 
     } 
 
     
 
    }) 
 
    
 
    app.controller('MainController', function($scope, SomeService){ 
 
     SomeService.generateEvent(); 
 
     $scope.$on('event:show', function(event, data){ 
 
      $scope.test = data.some; 
 
     }) 
 
    })
<div ng-app="core" ng-controller="MainController"> 
 
    {{test}} 
 
</div> 
 

 
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

+0

謝謝。它的工作,但問題是我的控制器不能在適當的時候調用函數generateEvent。那就是爲什麼我需要一個事件來通知控制器已經完成了一些事情。你有解決我的問題的想法嗎? – xroskam

+0

你能幫我描述一下你的邏輯嗎? –