mrusinak mrusinak - 1 year ago 146
Javascript Question

Angular-translate where translation contains directives

Is it possible to have embedded angular-js directives in translation values? I've been easily able to get embedded HTML to be show correctly by using the translate directive or service instead of the filter, and also getting dynamic values using the translate-directive with translate-value attributes.

I just ran into a problem where a translation item contained an embedded element marked with attributes for an angular popover library directive (such that the you can mouse over the word in the span and have a little tooltip pop-up) - while using the translate-filter properly applied the translated value to the page, when mousing over the span element nothing pops up; sure seems like the embedded popover directive is not active.

Example plunker -

Is this not possible with angular-translate, or a shortcoming of the popover library we're currently using?


Answer Source

So, after playing around for a few days, I've eventually settled on a modified version of implementing a "compile" directive that pops up around the web:

    .directive("translateCompile", ['$compile', '$rootScope', '$translate', function($compile, $rootScope, $translate){
            restrict: 'A',
            link: function(scope, element, attributes) {
                function doCompile() {
                    // Wrap the contents in a span to make sure $compile will successfully operate
                    var txt = "<span>" + $translate.instant(scope.translateCompile) + "</span>";

                    // Compile the translated content and set it at the element's HTML
                    $compile(txt)(scope, function(cloned, scope) {

                // Watch for translation changes, to regenerate
                $rootScope.$on('$translateChangeSuccess', doCompile);

                // Do initial compilation

... which allows it to be used such <h3 translate-compile="SOME_KEY"></h3>. Not sure if it's possible to simplify this at all (or if I did a no-no somewhere), but so far seems to do the trick.