2014-08-28 63 views
1

如何使用ng-include這樣的內容只會被加載一次? 以下是我有:AngularJS ng只包含一次

<div data-ng-if="%condition-1%" data-ng-include="%url-1%"></div> 
<div data-ng-if="%condition-2%" data-ng-include="%url-2%"></div> 
<div data-ng-if="%condition-3%" data-ng-include="%url-3%"></div> 
... 

在我來說,唯一的條件是真正的在一定的時間時刻。 任何情況都可以在頁面生命週期中多次更改其值。 因此ng-include會一次又一次加載相同的內容。 如何告訴Angular只處理ng-include一次 - 當適當的條件第一次變爲真時? 一次加載它們會導致頁面死機,因爲每個模板都很大很重。 也沒有嚴格的條件變化順序,例如,condition-3在頁面生命週期中可能永遠不會變爲真 - 在這種情況下,我不想加載url-3內容。 謝謝!

UPDATE 是的,模板已經在緩存中。但它有一個複雜的內部結構,如引用外部圖像,iframe等 - 所有這些東西都重新加載每次當我使用ng-include

+1

是不是模板放入緩存?否則,不能'ngShow'而不是'ngIf'工作? – Blackhole 2014-08-28 21:56:01

+1

它的'ng-if'.Template無論如何都會緩存在內部模板緩存中,一旦加載,問題是什麼。 – PSL 2014-08-28 21:56:41

回答

1

你有很多的解決方案,但只有2此刻

1°,我想起更換NG-如果一個NG-顯示,作爲NG-如果刪除DOM和所有兒童範圍內有效,迫使該框架再次提出請求,而如果您使用的是ng-show,dom只會被隱藏,並且請求只會被創建一次。

2°如果您確實需要使用ng-if並且服務器中的內容是靜態的,您可以通過手動訪問由angular提供的$ templateCache服務來緩存它,或者如果您希望加載是html,你可以在javascript層上使用$ templateCache服務,或者使用ng-template標籤預加載數據。

實施例:

<script id="url/you/want.html" type="text/ng-template"> 
<div>I am preloaded dom that responds to the url/you/want.html 
requests made by this application 
</div> 
</script> 

乾杯

0

如何僅使用一個NG-包括和使用一些邏輯控制器中的切換使用的結合使用哪個資源?這種方式一次只能裝載一個。

控制器

function($scope) { 
    $scope.activeTemplate = null; //some default or even null 

    $scope.$watch('condition', function(newvalue) { 

     //whatever logic you need to switch template 

     if (newvalue == 'condition1') { 
      $scope.activeTemplate = '/path/to/condition1.html'; 
     } else if (newvalue == 'condition2') { 
      $scope.activeTemplate = '/path/to/condition2.html'; 
     } else { 
      $scope.activeTemplate = '/path/to/default.html'; 
     } 
    }); 
} 

這樣,只有一個模板,將永遠在同一時間被加載,並且您已經減少綁定的數量從3比1(但是你已經如此有效地增加了手錶從3到2也許)