2014-10-27 29 views
10

我想在每次ng-include指令請求一個部分時更改url。到目前爲止,我能看到的網址,而該事件是這樣的:

app.run(function ($rootScope) { 
    $rootScope.$on('$includeContentRequested', function (event, url) { 
     console.log(event); 
     console.log(url); 
    }); 
}); 

現在我需要能夠將URL從'templates/incs/includedPartial.html'改變'templates/incs/includedPartial.html?cache_version=1_1',然後包括部分新鏈接。

顯然我這樣做是爲了防止版本更改時出現緩存問題。這是一個好策略還是有更好的解決方案?在此先感謝您的幫助...

回答

6

我想我其實想出了這個答案。你可以做的是創建一個攔截器。由於所有使用ng-include的請求實際上都經過了通用的$ httpProvider,因此您可以攔截請求並添加緩存攔截器。

app.factory("cacheBusterFactory", [ "VERSION", function(VERSION) { 
    return { 
     request: function(config) { 
      if(config.url.indexOf(".html", config.url.length - ".html".length) !== -1) { 
       config.url += "?v=" + VERSION.toString(); 
      } 

      return config; 
     } 
    }; 
} ]); 

「版本」,在這種情況下是一個角度不變,我更改每個部署:

app.constant("VERSION", 0.1); 

和增加緩存剋星是簡單的:

.config([ "$httpProvider", function($httpProvider) { 
    $httpProvider.interceptors.push("cacheBusterFactory"); 
} ]) 

正如你可以看到我只攔截.html文件,因爲這些是我需要添加緩存的唯一方法。您當然可以擴展或重建「cacheBusterFactory」以滿足您的需求。

0

我遇到了$templateCache和預定義模板(例如UI Bootstrap)的問題。我通過測試緩存來解決它。

app.factory("cacheBusterFactory", [ "$templateCache", "VERSION", function($templateCache, VERSION) { 
    return { 
     request: function(config) { 
      if(config.cache === $templateCache 
       && !angular.isDefined($templateCache.get(config.url))) !== -1) { 
       config.url += "?v=" + VERSION.toString(); 
      } 

      return config; 
     } 
    }; 
} ]);