2016-03-04 70 views
0

我需要使用ngInclude包含文件。 我的問題是,我想加載自定義視圖。如果這個customView不存在,我想使用默認的。ngInclude如果文件不存在,則使用默認路徑

我有一段代碼工作,但我認爲我可以做得更好......我想使用指令,我認爲它好得多。

HTML:

<div class="include-container" ng-include="{{ mainViewUrl }}"></div> 

控制器:

$http.get('customView.html').then(function success(response) { 
      $scope.mainView = "'customView.html'"; 
     }, function error(response) { 
      $scope.mainView = "'defaultView.html'"; 
     }); 

感謝您的幫助,我希望這不是一個重複的問題...

編輯:

我找到的解決方案這一部分:AngularJS ng-include failover 這裏Plunker

我想,對失敗,裝入我的默認網址。任何想法 ?

EDIT2:

我願做這樣的事情:

<div class="include-container" ng-include="customView.html || defaultView.html"></div> 
+0

好像會加載它兩次。你能注入一個字符串而不是文件嗎?你已經將文件內容作爲'get'部分中的一個字符串,如果不需要(不在代碼中顯示),應該是HEAD請求而不是GET – dandavis

+0

我會先將該調用放入工廠。響應包含的數據是什麼。我的意思是,你不使用它。爲什麼不?您不應該爲http調用使用指令。指令應該是你應用程序中的愚蠢組件。 – Michelangelo

+0

如果可能的話,我寧願使用別的方法,而不是http調用:)這是我迄今爲止發現的唯一方法...我將更新我的問題以顯示我使用的指令,但對我來說做得不夠 – carndacier

回答

0

把響應到$templateCache這樣的觀點不會使另一個請求得到同樣的文件

$http.get('customView.html').then(function success(response) { 
     $templateCache.put('customView.html', response.data); 
     $scope.mainView = "'customView.html'"; 
}, function error(response) { 
    $scope.mainView = "'defaultView.html'"; 
}); 
+0

好的...但我沒有看到它什麼時候可以請求兩次?有什麼使用可以完成的指令嗎? – carndacier

+0

會執行兩次請求,因爲'$ http'發出一個請求...那麼'ng-include' – charlietfl