AngularJs broadcast event

后端 未结 2 2037
小蘑菇
小蘑菇 2021-01-26 07:41

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

相关标签:
2条回答
  • 2021-01-26 07:52

    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.

    0 讨论(0)
  • 2021-01-26 08:05

    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

    0 讨论(0)
提交回复
热议问题