Dealing With Angulars Cache

This article is about how to circumvent AngularJS’ slightly irritating persistent cache, without suffering a performance hit.

When you have worked with AngularJS for a while, you’ve probably been in a situation where you have made a change to a template file (that is, a seperate .html-file), refreshed your browser of choice and been left wondering “Where’s that change I just made?”. What you have probably encountered is the AngularJS template cache. The most common solution to that problem, that I have found searching the web, is forcing AngularJS to delete its template cache all the time.

app.run(function($rootScope, $templateCache) {
    $rootScope.$on('$viewContentLoaded', function() {
        $templateCache.removeAll();
    });
});

This code will delete the template cache each time the page has loaded the content. That does the trick, but if you are concerned about performance, cleaning the cache all the time, will make you hair stand on edge. Fear not! There is an answer to your plea. Compile the templates into ONE file that you can control with version numbers. Now, it might sound difficult, but thanks to the wonderful gulp.js library, it is as easy as pie!
First, you install the gulp npm package. You can do so by following the “Getting Started” guide on their GitHub page. After you have installed gulp, you should install the gulp-angular-templatecache package with the npm install gulp-angular-templatecache command, and follow the guide and example they supply, and you’ll soon have a compiled version of all your template files. You can now versionate that file, and forget all the problems you ever had with the AngularJS template cache.