Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disable template caching in AngularJS with ui-router

I have noticed that from time to time I'll make a change to one of the templates within my AngularJS application and that at runtime, the change won't be visible. Rather, I'll have to refresh the application and if that fails, go to the path of the template itself and refresh it in order to see this change.

What's the best way to prevent caching of these templates like this? Ideally, I'd like them to be cached during the current use of the Angular application, but that the next time I load the page, they retrieve the latest and greatest templates without having to manually refresh.

I'm using ui-router if that makes any difference here. Thanks!

like image 251
Whit Waldo Avatar asked May 11 '14 06:05

Whit Waldo


Video Answer


2 Answers

You can use a decorator and update UI Router's $templateFactory service to append a suffix to templateUrl

function configureTemplateFactory($provide) {
    // Set a suffix outside the decorator function 
    var cacheBuster = Date.now().toString();

    function templateFactoryDecorator($delegate) {
        var fromUrl = angular.bind($delegate, $delegate.fromUrl);
        $delegate.fromUrl = function (url, params) {
            if (url !== null && angular.isDefined(url) && angular.isString(url)) {
                url += (url.indexOf("?") === -1 ? "?" : "&");
                url += "v=" + cacheBuster;
            }

            return fromUrl(url, params);
        };

        return $delegate;
    }

    $provide.decorator('$templateFactory', ['$delegate', templateFactoryDecorator]);
}

app.config(['$provide', configureTemplateFactory]);
like image 176
Aman Mahajan Avatar answered Oct 21 '22 15:10

Aman Mahajan


Above solution was great and was not working for template urls

function templateUrl: function($stataParams) { return '/serverUrl?id=' + $stataParams.id + '&cid=' + $stataParams.cid; }

fixed by

function templateFactoryDecorator($delegate) {
    var fromUrl = angular.bind($delegate, $delegate.fromUrl);
    $delegate.fromUrl = function (url, params) {
        if (url !== null && angular.isDefined(url)) {
            if (typeof url == 'function') {
                url = url.call(url, params);
            }
            if (angular.isString(url)) {
             url += (url.indexOf("?") === -1 ? "?" : "&");
             url += "v=" + Date.now().toString();
             }
         }

         return fromUrl(url, params);
     };

     return $delegate;
}
like image 45
Biju Thomas Avatar answered Oct 21 '22 16:10

Biju Thomas