5

I have following code, which basically loads messages from the server via $http.get request in the service and then used in the i18n filter. Filter was working fine with angular version 1.2.24 but after updating to 1.3.5 it no longer works.

I was wondering if anyone ran into similar issue and can shine some light on this.

var module = angular.module('myApp', [])

.factory('MessageFactory', function ($http, $locale, $log) {
    var messages = {};

    $http.get("/i18n/" + $locale.id + "/list", {cache: true}).success(function(data) {
        $log.debug("Getting messages for", $locale.id);
        messages = data;
    });

    return {
        getMessage: function (key) {
            return messages[key];
        }
    }
})

.filter('i18n', function (MessageFactory) {
    return function (key) {
        return MessageFactory.getMessage(key);
    }
});

Html Code

<h2>{{'message.page.title'|i18n}}</h2>

2 Answers 2

10

Finally after couple of hours of digging I changed

.filter('i18n', function (MessageFactory) {
    return function (key) {
        return MessageFactory.getMessage(key);
    }
});

to

.filter('i18n', function (MessageFactory) {
    function filterFn(key) {
        return MessageFactory.getMessage(key);
    }

    filterFn.$stateful = true;

    return filterFn;
});

Notice filterFn.$stateful that's what did the trick.

Sign up to request clarification or add additional context in comments.

1 Comment

didn't knew this, nice.
0

I couldn't find docs proof of that, but it looks like angular 1.3.x executes code inside modules only when it firstly used, and <= 1.2.x do it when app started.

Looks like you need to change your code to load locale files in app.run() method;

Something like this: http://codepen.io/anon/pen/vELogx

1 Comment

Tried that, the problem with the "run" approach is that the exception is thrown inside MessageFacotry.getMessage while messages is null. As soon as data from the $http.get is returned the filter works as expected.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.