Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS ng-bind to Dynamic Variable Name

I'm trying to accomplish something similar to this to add support for languages using AngularJS:

window.language = english;
$scope.title.english = "English thing";
$scope.title.spanish = "Espanol Si";

<h1 ng-bind="title.{{window.language}}"></h1>

Anyone know how to do something like this from within the template?

like image 661
ProfessorManhattan Avatar asked Apr 25 '26 22:04

ProfessorManhattan


1 Answers

there are mutliple ways of achieving this:

1 - logic in html:

JS

$scope.window = window;
$scope.title = {
    english: 'English thing',
    spanish: 'Espanol Si'
};

HTML

<h1 ng-bind="title[window.language]"></h1>

or

<h1>{{title[window.language]}}</h1>

but this will lead to a lot of code duplications and also you'll end up with no text at all for missing translations (and also no error)

2 - logic in controller

JS

var title = {
    english: 'English thing',
    spanish: 'Espanol Si'
};

$scope.getTitle = function() {
    // maybe add code for error handling here
    return title[window.language];
};

HTML

<h1 ng-bind="getTitle()"></h1>

or

<h1>{{getTitle()}}</h1>

this still leaves you with a lot of code duplications, but at least you can perform some validation logic and may throw an error on a missing validation (or provide some kind of fallback mechanism). additionally as it is now javascript code, it is easily testable as well.

3 - create a custom filter

JS - filter

angular
    .module('myI18n', [])
    .filter('my18n', function() {
        return function(data) {
            // add code for error handling etc. here
            return data[window.language];
        };
    });

JS - controller

$scope.title = {
    english: 'English thing',
    spanish: 'Espanol Si'
};

HTML

<h1 ng-bind="title | myI18n"></h1>

or

<h1>{{title | myI18n}}</h1>

this is probably the cleanest solution you can get, and it is also very expressive as you directly state in your html what should happen to your code, without relying on the implementation details (maybe you want to change window.language to window.i18n.language later on or something like that). also it is easily testable again.

So you if you really want to go with implementing something like this yourself, i would recommend the 3rd option, but you have to be aware that you are limited to synchronous translations. For a more sophisticated approach i would really recommend using a ready to use i18n library like angular-translate

like image 190
Thomas Scheinecker Avatar answered Apr 27 '26 11:04

Thomas Scheinecker



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!