Search code examples
javascripthtmlangularjsangular-translate

How to get translation ID from function in HTML using with angular-translate


I have an ng-repeat placing some images with a caption from an array:

<span ng-repeat="foo in bar">                   
   <p ng-click="myFunction(foo)" ng-init="imgsrc=foo.image">                                                    
      <img ng-src="{{imgsrc}}" style="cursor: pointer; cursor: hand"/>
      <br />
      <span >My Caption</span>                                                                                  
   </p>     
</span>

This works perfectly, but now I want to change the caption of each image based on the current language. I have angular-translate working like this:

<div translate>MY_TRANSLATION_ID</div>

But now I need to get the translations ID from my foo object in the loop. I tried:

  • <span translate>{{foo.translationID}}</span>
  • <span translate>foo.translationID</span>
  • Creating a function that will return the translation ID:
    <span ng-init="text=myTranslate(foo)">{{text}}</span>

But nothing works. Is this possible? I'm trying to avoid saving the translated string in my foo object directly because I'm using async loading and I'm changing the language dynamically so it's not that easy or I couldn't get it working properly (also as recommended here I should be doing my translations in my HTML code)


Solution

  • You can make use of translate filter:

    <span>{{ foo.translationID | translate }}</span>