Skip to content

jQuery Globalize and AngularJS Integration in Under 100 Lines

published: 

The other day I threw together a quick proof-of-concept for integrating AngularJS with the jQuery Globalize Plugin. The first part is a simple utility Angular “service” which loads the appropriate JSON message bundle:

factory("LocalizeConfig", [
    "$http",
    function ($http) {
        return {
            /**
             * @type {Array.<String>}
             */
            supportedLocales: [],

            /**
             *
             * @param {Array.<String>} locales
             */
            setSupportedLocales: function (locales) {
                this.supportedLocales = locales;
            },

            /**
             * Load localization data for the specified locale
             * @param {String} locale
             */
            initialize: function (locale) {
                var url, config;

                if (locale) {
                    if (this.supportedLocales.indexOf(locale) !== -1) {
                        currentLocale = locale;
                    } else {
                        throw new Error("Unsupported locale");
                    }
                }

                url = "l10n/" + currentLocale + "/messages.json";
                config = {
                    dataType: "json",
                };

                $http.get(url, config).then(function (response) {
                    var messages = response.data;
                    Globalize.addCultureInfo(currentLocale, {
                        messages: messages,
                    });
                    console.log(_.keys(messages).length + " locale messages added for " + currentLocale);
                });
            },
        };
    },
]);

It is bootstrapped from run() in app.js:

run([
    "$location",
    "LocalizeConfig",
    function ($location, localizeConfig) {
        var params = $location.search();
        localizeConfig.setSupportedLocales(["en_US", "de_DE"]);
        localizeConfig.initialize(params.locale);
    },
]);

Source code is available on Github. Just fire up launch.html to view the sample app initializing with different locales.

I’m still working on a more thorough evaluation of jQuery Globalize itself. Assuming it meets the criteria, a few more improvements come to mind:

Hope you found this one interesting!


tags: