2014-10-27 47 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; 
     } 
    }; 
} ]);