angular-translate: Translate dynamic value

2019-05-14 17:16发布

We're using angular-translate to translate our app.

Regular translations with dynamic number values are no problems, like

'LIVES_LEFT': 'You have {{ lives }} left.'

used like

<p>{{ 'LIVES_LEFT' | translate:player }}</p>

The problem comes when the dynamic value is a string that itself needs to be translated, like

'YOU_HAVE_A_CHILD': 'You have a {{ gender }} that is {{ age }} years old.'

Used like

<p>{{ 'YOU_HAVE_A_CHILD' | translate:child }}</p>

gender in this case should end up resolving to 'boy', or 'girl' if the selected language is English, and for example 'Junge', or 'Mädchen', if the selected language is German. How do I do that?

EDIT:

As suggested by Partha Sarathi Ghosh below I tried

<p>{{ 'YOU_HAVE_A_CHILD' | translate:(child | translate) }}</p>

But I get a syntax error from that:

Error: [$parse:syntax] Syntax Error: Token 'Object' is unexpected, expecting []] at column 9 of the expression [[object Object]] starting at [Object]].

However,

{
    'YOU_HAVE_A_CHILD': 'You have a {{ gender | translate }} that is {{ age }} years old.',
    'GENDER_BOY': 'boy',
    'GENDER_GIRL': 'girl'
}

used like

<p>{{ 'YOU_HAVE_A_CHILD' | translate:vm.childTranslationData() }}</p>

with Controller code like this:

function childTranslationData() {
    return {
        gender: vm.child.gender === 'boy' ? 'GENDER_BOY' : 'GENDER_GIRL',
        age: vm.child.age
    };
}

worked great! Thanks a lot!

1条回答
我只想做你的唯一
2楼-- · 2019-05-14 17:55

Try this. It may solve your problem.

{{ 'YOU_HAVE_A_CHILD' | translate:(child | translate) }}

Or you can try this

'YOU_HAVE_A_CHILD': 'You have a {{ gender | translate }} that is {{ age }} years old.'

If does not solve then translate child from your controller first

查看更多
登录 后发表回答