Using AngularJS and Angular Translate how do you check if a string has been translated?
Asked Answered
L

3

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?

Lamellate answered 1/12, 2013 at 16:0 Comment(0)
E
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>
Exonerate answered 6/12, 2013 at 14:24 Comment(4)
Your link is broken.Laflamme
@Laflamme fixed the linkExonerate
What if your translation and your key are actually the same?Oxblood
@Oxblood please have a look at my new answerExonerate
E
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.

Exonerate answered 16/1, 2018 at 15:35 Comment(0)
I
0

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

Iodic answered 9/1, 2019 at 11:7 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.