Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 939
xroskam Avatar asked Jul 02 '15 08:07

xroskam


People also ask

What is $emit $broadcast and $on in AngularJS?

The difference between $broadcast() and $emit() is that the former sends the event from the current controller to all of its child controllers. That means $broadcast() sends an even downwards from parent to child controllers. The $emit() method, on the other hand, does exactly opposite.

What is $on in AngularJS?

$. on is just a function that attaches an event listener. Read the docs. In my experience with AngularJS, which is admittedly limited, $on works nearly as same as the jQuery on function.

What is $emit in AngularJS?

$emit() Function. The AngularJS $emit method is used to dispatches an event name upwards and travel up to $rootScope. scope listeners. The $emit propagatesevent name upward and travel upwards toward $rootScope. scope listeners and calls all registered listeners along the way.

What is rootScope broadcast in AngularJS?

$broadcast in AngularJS? The $rootScope. $broadcast is used to broadcast a “global” event that can be caught by any listener of that particular scope. The descendant scopes can catch and handle this event by using $scope.


1 Answers

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>
like image 106
Ivan Burnaev Avatar answered Oct 20 '22 00:10

Ivan Burnaev