如何捕获角度ng-include错误

Tyl*_*ang 8 javascript angularjs angularjs-ng-include

当我ng-include用作标题时,如何在地址(文件路径)不存在时捕获错误?

我完成了一个ng-include router内部ng-view(with ng-route),它有点像这样:

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;
Run Code Online (Sandbox Code Playgroud)

ContentView:

<div ng-include="template.url" class="ng-animate"></div>
Run Code Online (Sandbox Code Playgroud)

当我使用addr时不存在如:/ home /#/ content/profile_asdfa,angular只是在循环中获取资源.所以当哈希中没有模板文件时,我需要捕获ng-include错误.有谁能够帮我 ?谢谢!

Mic*_*mza 13

查看ngInclude源代码,当模板不存在时,似乎没有挂钩或方法直接检测404(或其他)错误.您可能需要考虑添加此功能的功能请求,因为它听起来像一个有用的功能.

但是,现在你可以使用http响应拦截器做一些事情.如果有一种方法可以判断http reguest是否适用于模板,例如它位于"content"目录中,您可以拦截错误,并对它们执行某些操作.例如,您可以使用自定义指令替换数据,然后发出一个事件,以便控制器可以响应它.

拦截器可以写成:

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);
       }
    }
  }
});
Run Code Online (Sandbox Code Playgroud)

因此,当从'content'指令中获取内容后出现错误时,它会添加一个元素<template-error>来代替模板内容.当编译然后链接它时,它$emit是一个自定义事件,templateError父控制器可以响应$scope.$on.所以该指令可以编码如下:

app.directive('templateError', function() {
  return {
    restrict: 'E',
    scope: {
      'url': '='
    },
    link: function(scope) {
      scope.$emit('templateError', {url:scope.url});
    }
  };
});
Run Code Online (Sandbox Code Playgroud)

然后在原始的父控制器中ngInclude,您可以对此事件做出反应:

$scope.$on('templateError', function(e, data) {
  $scope.templateError = true;
  $scope.templateErrorUrl = data.url;
})
Run Code Online (Sandbox Code Playgroud)

您可以在此Plunker中看到完整的工作代码.虽然我认为这有点hacky,但如果Angular团队决定在错误$emit代码中添加ed事件ngInclude,那么删除拦截器/你的自定义元素应该很容易.