【发布时间】:2014-10-02 18:08:28
【问题描述】:
我创建了一个工厂来提供我自己的 Angular $exceptionHandler 实现。 该工厂在 $rootScope 上发出一个事件,向侦听器发出发生错误的信号。 我的侦听器是在监视 $rootScope.$on 事件的指令中定义的。就我的工厂实例拦截异常并发出错误事件而言,一切似乎都很好。但是,据称正在侦听事件的指令从未接收到所述事件。是什么断开导致监听器在指令中错过了这个事件??
澄清:事件完全依赖于 $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']);
【问题讨论】:
标签: javascript angularjs