2014-10-02 42 views
0

发出$ rootScope接收事件我已经创建了一个工厂提供我自己的实现角度的$ exceptionHandler的的。 此工厂在$ rootScope上发出一个事件来向侦听器发出发生错误的信号。 我的监听器在正在监视$ rootScope。$ on事件的指令中定义。一切似乎都很好,因为我的工厂实例拦截异常并发出错误事件。然而,据说听取该事件的指示从未接收到该事件。什么是导致该事件被指令中的监听器错过的断开连接?不是由我厂

澄清:该事件(eventing)依赖于发射和完全上$ rootscope消耗,以避免下游广播事件。这是通过设计和以前的工作,或者至少似乎工作在一个httpLoader和一个httpErrorHandler,我写的基于几个使用相同的策略的实现。 http://plnkr.co/edit/N0JwYJdxPLur4xYZTUP1?p=info

Plunker:http://plnkr.co/edit/LDbRa0Ew255fOd0EunAq?p=preview

angular.module('demo.services',[]); 
angular.module('demo.directives',[]); 
angular.module('demo',['demo.services','demo.directives']); 

angular.module('demo') 
.controller('demoCtrl', function($scope){ 
    $scope.message="Generate Error"; 
    $scope.generateError =function(){ 
    var x; 
    x.foo.oops = ':('; 
    } 
}); 

angular.module('demo.services') 
.factory('$exceptionHandler', function() { 
    var $injector = angular.injector(['ng']); 
    return function errorCatcherHandler(exception, cause) { 
     rootScope = $injector.get('$rootScope'); 
     rootScope.$emit("httpError",exception); 
     console.error(exception); 
    }; 
}); 


angular.module('demo.directives') 
.directive('ngHttpError', ['$rootScope', 
    function ($rootScope) { 
    return { 
     scope: { 
     title: '@', 
     }, 
     template: '<div ng-click="showError=false"' + 
       'ng-show="showError">'+ 
       'ERROR! {{errorModel | json}}' + 
       '</div>', 
     link: function ($scope) { 
     var showError; 

     $scope.showError = false; 
     $scope.errorModel = {}; 
     showError = $scope.showError; 

     var initScope = function(e,m){ 
      console.log(m); 
      $scope.errorModel = m; 
      $scope.showError=true; 
     } 
     $rootScope.$on("httpError", initScope); 
     } 
    }; 
    } 
]); 

angular.bootstrap(document,['demo']); 

回答

2

记住$emit()向上发送事件的范围层次和$broadcast()发送事件下的层次结构。由于$rootScope是“根”范围(最高级别/节点),这将是有意义的使用$broadcast()这里事件“向下”发送到子作用域。

$emit(),从the docs

通过作用域层级通知注册$ rootScope.Scope听众向上将事件调度名。

$broadcast(),从the docs

向下分派事件名称到所有子范围(和他们的子女)通知注册$ rootScope.Scope听众。

- 更新:

我已经更新您的$exceptionHandler获得注入的$injector服务,并做了$broadcast()而不是$emit()的 - 这似乎这样的伎俩:

angular.module('demo.services') 
.factory('$exceptionHandler', function ($injector) { 
    //var $injector = angular.injector(['ng']); 
    return function errorCatcherHandler(exception, cause) { 
     rootScope = $injector.get('$rootScope'); 
     rootScope.$broadcast("httpError",exception.message); 
     console.error(exception); 
    }; 
}); 

顺便说一句,一个相关的问题/答案可以在这里看到:AngularJs/ .provider/how to get the rootScope to make a broadcast?

+0

只有牛逼我不希望将事件广播到儿童范围。这包含的消息传递策略完全是以$ rootscope为目的的。请参阅:http://plnkr.co/edit/N0JwYJdxPLur4xYZTUP1?p=preview – mccainz 2014-10-02 18:19:54

+0

BTW:你测试,这是这个问题,并证实了它? – mccainz 2014-10-02 18:31:28

+0

好吧,我已经尝试从您的'generateError()'函数$广播 - 并且发射不工作(如预期根据我写在我的答案)。现在,我试图找出为什么从你的异常处理广播不起作用:) – 2014-10-02 18:33:11