AngularJs/ .provider / how to get the rootScope to make a broadcast?

感情迁移 提交于 2019-12-21 07:13:39

问题


Now my task is to rewrite $exceptionHandler provider so that it will output modal dialog with message and stop default event.

What I do:

in project init I use method .provider:

.provider('$exceptionHandler', function(){

//and here I would like to have rootScope to make event broadcast

})

standart inject method does not work.

UPD: sandbox - http://jsfiddle.net/STEVER/PYpdM/


回答1:


You can inject the injector and lookup the $rootScope.

Demo plunkr: http://plnkr.co/edit/0hpTkXx5WkvKN3Wn5EmY?p=preview

myApp.factory('$exceptionHandler',function($injector){
    return function(exception, cause){
        var rScope = $injector.get('$rootScope');
        if(rScope){
            rScope.$broadcast('exception',exception, cause);
        }
    };
})

Update: add .provider technique too:

app.provider('$exceptionHandler', function() {
  // In the provider function, you cannot inject any
  // service or factory. This can only be done at the
  // "$get" method.

  this.$get = function($injector) {
    return function(exception,cause){
      var rScope = $injector.get('$rootScope');
      rScope.$broadcast('exception',exception, cause);  
    }
  };
});



回答2:


My way of doing this - using a decorator and reverting to the previous exception handler on unknown errors:

app.config(function ($provide) {
  $provide.decorator('$exceptionHandler', function($delegate, $injector) {
    return function (exception, cause) {
      if (ICanHandleThisError) {
        var rootScope= $injector.get('$rootScope');
        // do something (can use rootScope)
      } else
       $delegate(exception, cause);
    };
  });
});



回答3:


You need to inject the $rootScope:

.provider('$exceptionHandler', '$rootScope', function(){

//and here I would like to have rootScope to make event broadcast

})

Is this what you tried? And if so do you have an error message or a jsfillde/plnkr to see why it failed?



来源:https://stackoverflow.com/questions/14954811/angularjs-provider-how-to-get-the-rootscope-to-make-a-broadcast

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!