【问题标题】:angularjs test if file exists for ng-includeangularjs测试ng-include的文件是否存在
【发布时间】:2013-07-29 18:10:50
【问题描述】:

我正在使用 ng-include 在 AngularJS 应用程序中引入部分内容。如果部分 .html 文件不存在,我想做点别的。

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

我将这些数据放入 $dialog,因此我无法使用典型的 routeProvider 功能 (afaik)。

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

相关问题:

angular - reusable dialogs

How to prepopulate a dialog in angularjs/bootstrap

【问题讨论】:

    标签: angularjs


    【解决方案1】:

    这样的事情可能会奏效。基本上 $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);
          });
        });
    });
    

    【讨论】:

    • 感谢您的建议。到目前为止,我一直没有使用 $http 模块。有没有办法只用 ng-include 来做到这一点?也许我可以给它打补丁?
    • 顺便说一句,AngularJS 还是新手,所以你说的可能是 AngularJS 的方式?
    • ng-include 在当前状态下基本上做同样的事情。你为什么不想使用 $http?
    • 没有真正的原因,只是不用担心。我会试试你的建议。
    【解决方案2】:

    我也有类似的需求,但发现内置的$templateCache & ui.router 的$templateFactory 行为不一致。当我使用这个...

    $templateFactory.fromUrl( './non-existant.html' )
    .catch( function( err ){ console.log( 'does not exist' )})
    

    ...它将无法触发 catch 回调。只有在两次点击此调用后才会触发错误。

    所以我使用$qXMLHttpRequest 推出了自己的解决方案:

    .service( 'templateUtils', [
        '$q'
        function( $q ){
            var api = {
                 hasTemplate: function( url ){
                      var d = $q.defer()
                      var rqst = new XMLHttpRequest()
                      rqst.open( 'GET', url )
                      rqst.onload = function( evt ){
                           if( evt.target.status === 200 )
                               d.resolve( true )
                           else
                               d.reject( false )
                      } 
    
                      return d.promise
                 }
            }
    
            return api
        }
    ])
    

    我就是这样用的……

    var templateUrl = './default-template.html'
    
    templateUtils.hasTemplate( urlToCheck )
    .then( function( rsp ){ templateUrl = './different-template.html' })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-17
      • 2013-04-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-16
      相关资源
      最近更新 更多