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.
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.
$. 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.
$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.
$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.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With