MojioMS MojioMS - 1 year ago 101
AngularJS Question

how to use an angular translationfilter inside a controller?

I have set up a translateProvider as follows:

.config(['$translateProvider', function($translateProvider){
$translateProvider.translations('en', {
'HELLO' : 'Hello'
$translateProvider.translation('de', {
'HELLO' : 'Hallo'

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:

.controller('ExampleController', [ '$scope', '$translate'], function($scope, $translate){
$scope.obj = {
translatedString = $translate('HELLO')

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

Answer Source

$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$translate