Skip to content Skip to sidebar Skip to footer

AngularJs Broadcast Event

I want to broadcast angular event from javascript function i.e angular.injector(['ng', 'myModule']).get('mySharedService').prepForBroadcast('hello'); By using above line I can invo

Solution 1:

angular.injector() creates a new injector, and with it a new $rootScope. The event will be broadcasted on this new $rootScope instead of on the one your controllers are listening on.

You need to retrieve the injector already associated with your application:

angular.element(domElement).injector();

You also need to manually trigger the digest loop for the data bindings to update, for example by using $apply.

Example:

angular.element(document).ready(function() {

  var element = angular.element(document.querySelector('.ng-scope'));
  var injector = element.injector();
  var scope = element.scope();

  scope.$apply(function() {
    injector.get('mySharedService').prepForBroadcast('hello');
  });
});

Demo: http://plnkr.co/edit/NDKBdzSmvN1xY7alafir?p=preview


Solution 2:

Another way of publishing events from one controller and listening them in other controllers would be to use angular-PubSub module.

The PubSub makes only subscribers to listen to the published events unlike the $rootScope.$broadcast in which it sends event to all the Scopes in Scope hierarchy making it inefficient as compared to the PubSub approach.


Post a Comment for "AngularJs Broadcast Event"