javascript - 如何捕获 Angular ng-include 错误

标签 javascript angularjs angularjs-ng-include

当我使用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/

相关文章:

javascript - 防止任何 Ajax XHR GET 在页面加载时返回 500 错误

javascript - 使用 AngularJS ui-router 创建一个类似状态的弹出窗口

javascript - 尽管 ng Include angularjs 不会显示 html 父内容

angularjs - ng-show 不与 ng-include 一起使用

javascript - 如何为带有一些特殊符号的数字创建 JavaScript 正则表达式

javascript - 如何从 iframe src 获取哈希值?

javascript - 如何从 Protractor 测试发出 POST 请求?

javascript - Angular js 简单 ng-include 不起作用

php - 缺少语法错误),不知道将其放置在哪里才能回显输入

angularjs - 如何在 Angular js 中支持 IE8 和 IE9 中的占位符属性而不依赖 jQuery?