Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angularjs - how to clear $routeProvider's caches of templateUrl

Tags:

angularjs

I have really basic use case in my app where I use AngularJS (1.0.8) for front end and Grails for back end. In the app layout I have a language switcher which allows the user to change the language. Switching the language, it does new http request to retrieve the page. Grails renders all language related stuff (i.e. labels) properly translated. This only works for Chrome, FF, and so but not for IE. IE renders proper language just for layout which is rendered by the main request.

I located the problem. I have defined $routeProvider where I load major of the app content. It is cached by default, therefore IE doesn't load templateUrl of $routeProvider because it loads them from cache:

myApp.config(function ($routeProvider) {
        $routeProvider.
            when('/', {controller: 'MyCtrl', templateUrl: '/eshop/myConfig'})
});

What I don't get is why it works in all other browsers.

I found some post how to clear cache but they doesn't work for me. Is there any solution for me? If not, I find $routeProvider completely useless for my use case. Post I found:

  • angularjs clear history when view loaded
  • AngularJS disable partial caching on dev machine
like image 265
kuceram Avatar asked Nov 29 '13 11:11

kuceram


2 Answers

Below should do it. You can manipulate angularjs's template caches by using $templateCache, so $routeProvider will load the template as new every time you access the controller.

myApp.config(function ($routeProvider) {
        $routeProvider.
            when('/', {controller: 'MyCtrl', templateUrl: '/eshop/myConfig'})
})

.controller('MyCtrl', function ($scope, $templateCache) {
    $templateCache.remove('/eshop/myConfig');
    // or
    $templateCache.removeAll();
});
like image 127
KinoP Avatar answered Oct 21 '22 14:10

KinoP


I was having the same issue with $routeProvider. And yes, the $templateCache does not help in this situation. Instead of keeping finding the real 'cache' source, I added the stamp parameter after the templateUrl. In my code:

$routeProvider.
        when('/', {templateUrl: '../views/home.html?v='+window.buildNumber, controller: 'HomeCtrll'}).
        when('/report', {templateUrl: '../views/form.html?v='+window.buildNumber, controller: 'FormCtrll'}).
        otherwise({redirectTo: '/'});

Sadly, I used a global variable "buildNumber" to save my life. Because I also use RequireJS for my AngularJS project, so this "buildNumber" will also be added to every dependency JS file by using the code:

require.config({
    urlArgs: "v=" + window.buildNumber,
    paths: {....}
});

Then every time the JS source or template html has been changed, I will only need to update that "buildNumber" in global scope. This is just a thought for the future updates in production environment. Hope this helps.

like image 39
Peng Avatar answered Oct 21 '22 12:10

Peng