Change source url on $includeContentRequested
Asked Answered
G

2

10

I want to change the url each time a ng-include directive requests a partial. So far I'm able to see the url and the event like this:

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

Now I need to be able to change the url from 'templates/incs/includedPartial.html' to 'templates/incs/includedPartial.html?cache_version=1_1', then include the partial with the new link.

Obviously I'm doing this to prevent caching problems on version change. Is this a good strategy or is there a better solution? Thanks in advance for any help...

Graph answered 27/10, 2014 at 11:1 Comment(0)
L
6

I think I actually figured out the answer to this. What you can do is to create an interceptor. Since all requests with ng-include actually goes through the generic $httpProvider you could intercept the request and add the cache buster.

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;
        }
    };
} ] );

"VERSION" in this case is an angular constant that I change on each deploy:

app.constant( "VERSION", 0.1 );

And adding the cache buster is as simple as:

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

As you can see I only intercept .html files since those are the only ones I need to add cache busting to. You could of course extend or rebuild the "cacheBusterFactory" to suit your needs.

Lusatian answered 3/11, 2015 at 8:49 Comment(0)
M
0

I have had a problem with the $templateCache and predefined templates (ex. UI Bootstrap). I have solved it by testing the cache.

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;
        }
    };
} ] );
Martainn answered 8/9, 2017 at 7:23 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.