AngularJs broadcast event

后端 未结 2 2087
小蘑菇
小蘑菇 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 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

提交回复
热议问题