Angular JS – i18n Directive + Dynamic Templates

angular.module("myApp.directives").directive("i18n", function () {
    return {
        restrict: "E",
        replace: true,
        scope: {
            key: "@"
        },
        template: function (elem) {
            if (elem.attr("html") == "true") {
                return "<span ng-bind-html='value'></span>";
            } else {
                return "<span>{{value}}</span>";
            }
        },
        controller: ["$locale", "$scope", function ($locale, $scope) {
            if ($scope.key == "CURRENCY_SYM") {
                $scope.value = $locale.NUMBER_FORMATS.CURRENCY_SYM
            } else {
                $scope.value = $locale.labels[$scope.key];
            }
        }]
    }
});

It’s possible to do the same with the templateUrl property, in order to load a different external template depending on some condition (the $locale language for instance).

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s