私は Angular 1.08 を使用しているため、使用する必要がありますresponseInterceptors
。
まずはコード。
通訳者:
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');
});
通知サービス:
app.service("NotificationService", function () {
var error = '';
this.setError = function (value) {
error = value;
}
this.getError = function () {
return error;
}
this.hasError = function () {
return error.length > 0;
}
});
ディレクティブ エラー ボックス:
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();
}
});
}
}
});
問題:<error-box>
複数の場所で使用すると、これらすべてのボックスにエラー メッセージが表示されます。これは私の意図ではありません。例外が発生したエラーボックスのみを表示したいと思います。
たとえば、トランザクションのリストを表示するディレクティブがあります。トランザクションの取得に失敗した場合、その部分で宣言されているエラーボックスを表示したい。また、顧客を編集できるディレクティブもあります。このディレクティブには、エラー ボックス タグも含まれています。
顧客の保存に失敗すると、両方のエラー ボックスが表示されますが、顧客のエラー ボックスのみを表示したいのです。
誰かがこれを実装するアイデアを持っていますか?