Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change source url on $includeContentRequested

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...

like image 763
s.alem Avatar asked Oct 27 '14 11:10

s.alem


1 Answers

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.

like image 126
musse1 Avatar answered Oct 04 '22 21:10

musse1