27

I'm trying to translate my project into another language. I used angular translate library and provided an external JSON file with the translations. It looks like this:

{
  "hello_world": "Hola Mundo"
}

When I'm using it with simple hardcoded strings it works just fine and I get my correct translations:

<p>{{ "hello_world" | translate }}</p>

But how to deal with the ternary operator in code like this?

<button> {{ conditionValue ? 'Show' : 'Hide' }} </button>

How to change those 'Show' and 'Hide' values into a translation filter with Angular Translate? I tried different ways but I got an invalid syntax errors. Thanks!

Luchnik
  • 1,067
  • 4
  • 13
  • 31
  • Possible duplicate of [How do I used angularjs translator conditionally for HTML label](https://stackoverflow.com/questions/32781875/how-do-i-used-angularjs-translator-conditionally-for-html-label) – Thusitha Sep 21 '17 at 18:12

5 Answers5

83

I think if you wrap the ternary operator into (), it will work.

<button> {{ ( conditionValue ? 'Show' : 'Hide' ) | translate }} </button>
Suren Srapyan
  • 66,568
  • 14
  • 114
  • 112
4

you may try for this:

here i make username online and offline when you choose soanish, the user online status will change into spnish based on ternary condition.

https://plnkr.co/edit/o16dpI?p=preview

[https://plnkr.co/edit/o16dpI?p=preview][1]

{{ ( userName ? 'Show' : 'Hide' ) | translate }}
Kunvar Singh
  • 1,779
  • 2
  • 13
  • 21
1

I've just come up with the solution! For ternary operators we have to use 'translate' directive instead of filter. And it works just fine:

{
  "show_value": "Show",
  "hide_value": "Hide",
}

<button translate> {{ conditionValue ? "show_value" : "hide_value" }} </button>
Luchnik
  • 1,067
  • 4
  • 13
  • 31
1

Here is your language JSON file

"CONFIGURATION": {
    "NEW_TEMPLATE": "New Template",
    "EDIT_TEMPLATE": "Edit Template"
}

CASE-I (With HTML tag)

<button> {{ ( variable === '5' ? 'CONFIGURATION.NEW_TEMPLATE' : 'CONFIGURATION.EDIT_TEMPLATE' ) | translate }} </button>

CASE-II (With some third party attribute)

<p-dialog header="{{(variable === '5' ? 'CONFIGURATION.NEW_TEMPLATE' : 'CONFIGURATION.EDIT_TEMPLATE') | translate}}"> 
Muhammad Bilal
  • 1,840
  • 1
  • 18
  • 16
0

If exist prefix

{{ ('massmedias.' + (ctrl.actionType === 'add' ? 'add' : 'rename')) | translate }}