angularjs测试ng-include是否存在文件

Jos*_*itt 5 angularjs

我正在使用ng-include在AngularJS应用程序中引入部分内容.如果部分.html文件不存在,我想做其他事情.

部分名称是从$ location.path()中提取的.所以如果路径是"/ foo",那么我想使用"my_partial_foo.html".但是,如果"my_partial_foo.html"不存在,那么我想改用"my_partial_default.html".

我将这些数据放入$对话框中,因此我无法使用典型的routeProvider功能(afaik).

我的主要问题是:在我使用ng-include指令之前,如何确定"my_partial_foo.html"是否存在?

相关问题:

角度 - 可重用的对话框

如何在angularjs/bootstrap中预填充对话框

mdo*_*010 3

像这样的东西可能会起作用。基本上 $templateCache 将始终有一个 my_partial_foo.html 的键(因此您的 ng-include 始终可以引用它),但该值可能是默认值或真实值。

var app = angular.module('myapp', []).run(function($templateCache,$http){
  $http.get('my_partial_foo.html',
    //success
    function(data){
      $templateCache.put('my_partial_foo.html', data);
    },
    //failure
    function(){
      $http.get('my_partial_default.html', function(data){
        $templateCache.put('my_partial_foo.html', data);
      });
    });
});
Run Code Online (Sandbox Code Playgroud)