Invalidating Angular template cache with .net BundleConfig.cs

You most probably had the problem with old Angular templates not clearing themselves up from the browser cache in production which can cause various problems. If you’re using gulp, you can use something like gulp-angular-templatecache to tackle this problem (which would also be a preferred way of doing this) but if you’re using .net’s BundleConfig.cs to bundle your scripts, you’ll have to add a bit of code to your app.

Say your app bundle section inside BundleConfig.cs looked something like this:

Then you would include that inside your index.cshtml (or some other Razor template) like this:

And this is how the generated HTML script include tag would look in production:

<script src=”/bundles/my-app?v=6XgTJerMdBNglpDE1l_sgb9JgKJDXS35tee8zasXvLk1″></script>

What changes upon every deploy is the “v” (version) hash at the end of bundle link. We can leverage that to keep track of the current version by extracting and storing that value within a cookie. Then on a full page reload (F5) if the version hash changed – we can simply clear the template cache and let the user continue using the app. The app will then have to re-cache all the templates once they are requested by the router or a directive.

That piece of logic can be stored inside app.js on MyApp.run(). Here is how I did it:

NOTE: I use lodash in every project so if you’re not using it, you might have to write your own code to replace _.find() and _.contains()