xroskam
xroskam

Reputation: 61

angularjs: broadcast event from service

I would like to create a custom event in angularjs. The goal is that the event will be broadcast by a service and must be catched in a controller.

I have in my service :

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

and my controller :

$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");
});

But I can't catch events in controller. console.log('event') is shown but I can't catch any events. Could someone explain me how to do that please? $rootScope is correctly declared in the service and in the controller.

Upvotes: 6

Views: 9521

Answers (1)

Ivan Burnaev
Ivan Burnaev

Reputation: 2730

Checkout a working demo:

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>

Upvotes: 12

Related Questions