MojioMS MojioMS - 3 months ago 18
AngularJS Question

how to use an angular translationfilter inside a controller?

I have set up a translateProvider as follows:

angular.module('app')
.config(['$translateProvider', function($translateProvider){
$translateProvider.translations('en', {
'HELLO' : 'Hello'
});
$translateProvider.translation('de', {
'HELLO' : 'Hallo'
});
$translateProvider.prefferedLanguage('en');
}])


and I can translate strings in HTML using expression with the filter successfully like:

{{ 'HELLO' | translate }}


shows up 'Hello' (or 'Hallo' depending on the preferred language setup).

How can I use that filter now in Javascript, let's say, in a controller?

My current approach is not working:

angular.module('app')
.controller('ExampleController', [ '$scope', '$translate'], function($scope, $translate){
$scope.obj = {
translatedString = $translate('HELLO')
};
});


as it shows up [object Object] instead the translation for 'HELLO'.

Answer

$translate is asynchronous and it returns promise instead of translated string so it can be used like this:

$translate('HEADLINE_TEXT').then(function (translation) {
  $scope.translatedText = translation;
});

More info https://angular-translate.github.io/docs/#/api/pascalprecht.translate.$translate