这是我可以包含在任何控制器中的工厂,以便他们可以监听响应错误:
$.validator.addMethod('isInteger', function (value, element, parameterValue) {
if ($(element).attr('data-badinput')) {
//We know nasty browser always clears incorrect input, so empty string will look OK next time
$(element).removeAttr('data-badinput');
return false;
}
return !value || /^-?\d+$/.test(value);
});
每种错误类别的两个模态面板:
app.factory('AuthInterceptor', function ($q, $injector) {
return {
responseError: function (res) {
var $modal = $injector.get('$modal');
if (res.status === 401) {
var modalInstance = $modal.open({
animation: true,
templateUrl: 'reLoginPanel',
backdrop: true
});
}
if (res.status === 403 || 404) {
$scope.msg = res;
var modalInstance = $modal.open({
animation: true,
templateUrl: 'infoPanel',
backdrop: true,
resolve: {
msg: function () {
return $scope.msg;
}
}
});
}
return $q.reject(res);
}
};
});
app.config(['$httpProvider',function($httpProvider) {
$httpProvider.interceptors.push('AuthInterceptor');
}]);
我收到以下错误:
<script type="text/ng-template" id="reLoginPanel">
<h1>Session expired</h1>
<p style="word-break: break-all;white-space: normal;">
To preserve unsaved data: Re-login with the following button. On Successful login close the new window and resume to this one. To close this message click outside this message box.
</p>
<div>
<form class="omb_loginForm" action="/auth/enticate/google" target="_blank" autocomplete="off" method="POST">
<button class="btn btn-lg btn-primary btn-block" type="submit">Log in with Google</button>
</form>
</div>
</script>
<script type="text/ng-template" id="infoPanel">
<h1>Warning</h1>
<span class="glyphicon glyphicon-info-sign"></span>
<br>
<p style="word-break: break-all;
white-space: normal;">
{{msg.data}}
</p>
</script>
&#39; msg.data&#39;无法从模板端访问。
如果我将$ scope添加到服务中:
Error: $scope is not defined
我收到以下错误:
app.factory('AuthInterceptor', function ($scope, $q, $injector)...
面板打开和关闭很好。
答案 0 :(得分:0)
您不需要使用任何范围:
app.factory('AuthInterceptor', function ($q, $modal) {
return {
responseError: function (res) {
if (res.status === 401) {
var modalInstance = $modal.open({
animation: true,
templateUrl: 'reLoginPanel',
backdrop: true
});
}
if (res.status === 403 || 404) {
var msg = res;
var modalInstance = $modal.open({
animation: true,
templateUrl: 'infoPanel',
backdrop: true,
controller : function($scope){
//your controllers code
}
resolve: {
msg: function () {
return msg;
}
}
});
}
return $q.reject(res);
}
};
});
编辑:添加了charlietfl的主张 edited2:添加了控制器