Wednesday, 19 February 2014

Safely Prevent Template Caching in AngularJS

AngularJS's $templateCache can be a pain in the ass. Sometimes we don't want templates to be cached. A quick Internet search to disable caching gives the following workaround:

But as I have learnt with the UI Bootsrap module, this may cause AngularJS modules that use $templateCache to break. A solution is to tweak the above workaround so that new cache entries are removed on route change instead of indiscriminately removing all entries:


  1. Hey one query, will the above change forcefully flush template HTML from browser cache also ?

  2. Thanks, app(2).js works in ionic app. Nice ! :)

  3. What if My templateUrl contains function

  4. did not work for me, still have to clear the browser cache manually every time i make any simple change.

  5. This comment has been removed by the author.

  6. I think I found an updated option for this:

    // Execute every time a state change begins
    $rootScope.$on('$stateChangeStart', function (event, toState, toParams, fromState, fromParams) {
    // If the state we are headed to has cached template views
    if (typeof (toState) !== 'undefined' && typeof (toState.views) !== 'undefined') {
    // Loop through each view in the cached state
    for (var key in toState.views) {
    // Delete templeate from cache
    console.log("Delete cached template: " + toState.views[key].templateUrl);

    P.S. I use $stateChangeStart because I use ui-router. You do not have to change $routeChangeStart if you do not want to.