6

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.

1 Answer 1

12

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>

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you. It work but the problem is that my controller can't call the function generateEvent at the good time. That why I need an event to inform the controller that something is done. Do you have an idea to solve my problem?
Can you get me a peace of code which describes your logic?
I think this answers the question properly. Obviously, you wouldn't emit the event in the same context as where you declare you listener but I feel we get the point.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.