4

The core issue here is that I can't inject $cookies into a config block, and configuring static file loading in Angular Translate seems to only be able to be done in a config block. I have a cookie containing my app version that I'd like to use as a query parameter for my static translation files to have a form of cache busting in between releases.

Here's the code:

(function( ) {
    'use strict';

    angular.module( 'vcp.core' ).
        config( configureTranslationResources );

    function configureTranslationResources( $translateProvider ) {

        var $cookies;
        angular.injector(['ngCookies']).invoke(['$cookies', function(_$cookies_) {
            $cookies = _$cookies_;
        }]);

        var vcpVersion = $cookies ? $cookies.get('vcp-version') : '';

        $translateProvider.useStaticFilesLoader({
            prefix: '/v2/assets/i18n/',
            suffix: '.json?v=' + vcpVersion
        });

    }

})( );

This feels odd and like there should be a better way. I can't intuit from the Angular Translate docs how to configure static file loading in a run block (not that that feels much better than this approach), and there doesn't appear to be a way to get at a cookie within a config block through $cookiesProvider.

Perhaps this approach altogether is a bad idea and there's a better way to solve the problem?

Daniel Allen
  • 894
  • 1
  • 10
  • 23

1 Answers1

2

If your page is dynamically generated, you could put the version number in the HTML instead of a cookie. For example, in index.html in a one-page app:

<script>
'use strict';
angular.module('vcp.settings', [])
.constant('vcpVersion', '{{vcp_version}}');
</script>

Where vcp_version is injected server-side. Since it's static for the duration of a deployment, your server can cache the generated HTML.

Constants are available during configuration, so you can inject the version number into your config function like this:

angular.module( 'vcp.core', ['vcp.settings'] ).
    config( configureTranslationResources );

function configureTranslationResources( $translateProvider, vcpVersion ) {
    ...
z0r
  • 8,185
  • 4
  • 64
  • 83
  • 2
    Great idea, thank you. Even if it weren't dynamically generated (which in this case it isn't) I could use a build tool to plop it in index.html and still use the same idea of making it a constant, which seems much cleaner than setting it in a cookie and passing it around that way. – Daniel Allen May 02 '16 at 15:02