Angularjs 1.3 asynchronous filter does not work

I have the following code, which basically downloads messages from the server via the $ http.get request in the service, and then uses it in the i18n filter. The filter worked fine with angular version 1.2.24, but after upgrading to 1.3.5 it no longer works.

I was wondering if anyone would encounter a similar problem and could illuminate this light.

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>
+4
source share
2 answers

Finally, after several 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;
});

Pay attention to filterFn. $ stateful , which was a trick.

+9
source

docs , , angular 1.3.x , , <= 1.2.x , .

, , app.run();

- : http://codepen.io/anon/pen/vELogx

0

All Articles