8

How do you check if a string has a translated value? I'm using AngularJS and AngularTranslate.

I only want to display a value if it has a been translated. Angular Translate will show the untranslated string if no translation is available.

I started off doing this:

<div ng-if="question.text | translate != question.text">{{ question.text | translate }}</div>

But this doesn't work as the comparison happens before the translate filter has done it's work. (At least I think that is what happens).

What I ended up doing is:

  .filter('isTranslated', function(){
return function(translatedVal, originalVal){
  return (translatedVal === originalVal) ? false : true;
}

})

<div ng-if="question.text | translate | isTranslated:question.text">{{ question.text | translate }}</div>

This works fine but I am wondering if there is a better way of doing this?

Paulo Fidalgo
  • 21,709
  • 7
  • 99
  • 115
Neil
  • 8,925
  • 10
  • 44
  • 49

3 Answers3

7

Angular-translate also provides a service, so you could build your own filter around it:

.filter('myTranslate', function($translate){
   return function(key){
      var translation = $translate(key);
      if(translation==key) {
         return "";
      } else {
         return translation;
   }  
}

This will make your HTML much cleaner:

<div>{{ question.text | myTranslate }}</div>
Pieter Herroelen
  • 5,977
  • 2
  • 29
  • 37
0

Since some time now you can use a custom error handlerhttps://angular-translate.github.io/docs/#/guide/17_custom-error-handler to return an empty string if no translation is found.

Pieter Herroelen
  • 5,977
  • 2
  • 29
  • 37
0

*ngIf="!(question.text | translate)"

BaronBaleron
  • 151
  • 1
  • 2