I want to broadcast angular event from javascript function i.e angular.injector([\'ng\', \'myModule\']).get(\"mySharedService\").prepForBroadcast(\'hello\'); By using above line
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