8

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

我完成了一个ng-include router里面的 a ng-view(with ng-route),有点像这样:

内容控件

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;

内容视图

<div ng-include="template.url" class="ng-animate"></div>

当我使用 addr 时,例如:/home/#/content/profile_asdfa,角度只是在循环中获取资源。因此,当哈希中没有模板文件时,我需要捕获 ng-include 错误。有谁能够帮我 ?谢谢!

4

1 回答 1

13

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

但是,现在您可以使用 http 响应拦截器来做一些事情。如果有某种方法可以判断 http 请求是否用于模板,比如它在“内容”目录中,您可以拦截错误,并对它们进行处理。例如,您可以用自定义指令替换数据,然后发出一个事件,以便控制器可以响应它。

拦截器可以这样写:

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);
       }
    }
  }
});

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

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

然后在原来的父控制器中ngInclude,可以对这个事件做出反应:

$scope.$on('templateError', function(e, data) {
  $scope.templateError = true;
  $scope.templateErrorUrl = data.url;
})

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

于 2013-12-30T11:38:07.617 回答