当我使用ng-include
作为标题时,地址(文件路径)不存在时如何捕获错误?
我在 ng-view(with ng-route)
中完成了一个 ng-include router
,
有点像这样:
ContentCtrl:
var content = $route.current.params.content,
tmplArr = content.split("_"),
tmpl = {},
personId=$route.current.params.personId||$scope.persons[0].id;
$scope.personId=personId;
tmpl.url = "content/";
for (var i = 0, len = tmplArr.length; i < len; i++) {
tmpl.url += tmplArr[i] + "/";
}
tmpl.url = tmpl.url.substring(0, tmpl.url.length - 1) + ".html";
$scope.template = tmpl;
内容 View :
<div ng-include="template.url" class="ng-animate"></div>
当我使用不存在的地址时:/home/#/content/profile_asdfa, Angular 只是在循环中获取资源。 所以当散列中没有模板文件时,我需要捕获 ng-include 错误。 有谁能够帮助我 ?谢谢!
最佳答案
在 source for ngInclude 中查找,当模板不存在时,似乎没有钩子(Hook)或方法可以直接检测 404(或其他)错误。您可能需要考虑添加此功能的功能请求,因为这听起来像是一项有用的功能。
但是,现在您可以使用 http 响应拦截器做一些事情。如果有某种方法可以判断 http reguest 是否用于模板,比如说它在“content”目录中,您可以拦截错误,并对它们进行处理。例如,您可以用自定义指令替换数据,然后发出一个事件,以便 Controller 可以响应它。
拦截器可以这样写:
app.config(function ($httpProvider) {
$httpProvider.interceptors.push('templateInterceptor');
});
// register the interceptor as a service
app.factory('templateInterceptor', function($q) {
return {
'responseError': function(rejection) {
var isTemplate = !!rejection.config.url.match(/^content/g);
if (isTemplate) {
rejection.data = '<div><template-error url="\''+ (rejection.config.url) + '\'"><strong>Error from interceptor.</strong></template-error></div>';
return rejection;
} else {
return $q.reject(rejection);
}
}
}
});
因此,当从“content”指令中获取内容后出现错误时,它会添加一个元素 <template-error>
代替模板内容。编译然后链接时,它 $emit
这是一个自定义事件,templateError
,哪些父 Controller 可以响应,由 $scope.$on
.所以该指令可以像这样编写代码:
app.directive('templateError', function() {
return {
restrict: 'E',
scope: {
'url': '='
},
link: function(scope) {
scope.$emit('templateError', {url:scope.url});
}
};
});
然后在原来的父 Controller 中ngInclude
,您可以对此事件作出 react :
$scope.$on('templateError', function(e, data) {
$scope.templateError = true;
$scope.templateErrorUrl = data.url;
})
你可以看到 full working code in this Plunker .虽然我认为这有点 hacky,但如果 Angular 团队决定添加一个 $emit
将事件编辑为 ngInclude
的代码如果出错,那么删除拦截器/您的自定义元素应该很容易。
关于javascript - 如何捕获 Angular ng-include 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20836374/