I'm using Angular 1.08, hence I need to use responseInterceptors.
First the code.
Interpreter:
app.factory('errorInterceptor', ['$q', 'NotificationService', function ($q, NotificationService) {
return function (promise) {
return promise.then(function (response) {
// do something on success
return response;
}, function (response) {
// do something on error
alert('whoops.. error');
NotificationService.setError("Error occured!");
return $q.reject(response);
});
}
}]);
app.config(function ($httpProvider) {
$httpProvider.responseInterceptors.push('errorInterceptor');
});
NotificationService:
app.service("NotificationService", function () {
var error = '';
this.setError = function (value) {
error = value;
}
this.getError = function () {
return error;
}
this.hasError = function () {
return error.length > 0;
}
});
Directive error-box:
app.directive("errorBox", function (NotificationService) {
return {
restrict: 'E',
replace: true,
template: '<div data-ng-show="hasError">{{ errorMessage }}</div>',
link: function (scope) {
scope.$watch(NotificationService.getError, function (newVal, oldVal) {
if (newVal != oldVal) {
scope.errorMessage = newVal;
scope.hasError = NotificationService.hasError();
}
});
}
}
});
The problem: When I use <error-box> at multiple places, all these boxes will display the error message. This is not my intent. I'd like to show only the error-box where the exception occurs.
For example, I have a directive which shows a list of transactions. When fetching the transactions fails, I want to show the error-box which is declared in that part. I also have a directive where I can edit a customer. This directive also contains the error-box tag.
What happens is when saving a customer fails, both error-boxes are displayed, however, I only want the error-box of the customer to be displayed.
Does someone has an idea to implement this?