Search code examples
javascriptangularjsangularjs-directiveangular-translate

Load directive based on translation string


So I want to insert a directive into the html page based on the translation that comes from angular-translate. Lets say I have these two directives:

.directive('englishText', function() {
  return {
    template: 'Hello'
  };
});
.directive('spanishText', function() {
  return {
    template: 'Hola'
  };
});

And I have these two json files from which will the translation come:

english.json
{
"LANGUAGE" : "english-text"
}

spanish.json
{
"LANGUAGE" : "spanish-text"
}

So on the html page I want to have something like that:

<div {{'LANGUAGE' | translate}}></div>

But as an output I jsut get this:

<div {{'language' | translate}}></div>

instead of

<div english-text>Hello</div>

I also tried this:

<{{'LANGUAGE' | translate></{{'LANGUAGE' | translate}}>

But I get this as an output

<english-text>

Which is interpreted just like an innerHTML and not like a tag...


Solution

  • If you insist on doing it the way you've asked this is the way to do it, the parent directive will $compile a language based directive and replace the inner html to the new directive

    .directive('languageDirective', function($compile) {
        return {
            restrict: 'EA',
            link: linkFn,
            scope: {
                language: '@'
            }
        };
    
        function linkFn(scope, element, attrs) {
            element.html(
                $compile(getTemplate)($scope)
            );
        }
    
        function getTemplate() {
            if(scope.language === 'english')
                return '<div english-directive></div>'
            else
                return '<div other-directive></div>'
        }
    });