How to pass parameters in angular-translate

JavascriptAngularjs

Javascript Problem Overview


I have created a function that does some error checkings and will be used in different input fields. My function code is below:

errorChecks = (element, minlength) => {
   if (element.$dirty) {
      if (element.$error.required == true) {
         this.errorMessage = "REQUIRED";
         return;
      } else if (element.$viewValue.length < minlength) {
          this.errorMessage = "MINLENGTH" // MINLENGTH error with parameters here
          return;
      } else {
          this.errorMessage = null;
          return;
      } 
   }
}

I am using the angularjs translate for my error messages.

"MINLENGTH": "{{ element }} must be at least {{ value }} characters",

I wanted to dynamically change my error message by passing a parameter to the translations like so:

errorChecks(username, 5);

If I enter 1 character to the username field the error would say: username must be at least 5 characters.

Is what I am trying to do even possible?

Javascript Solutions


Solution 1 - Javascript

It'll probably be best if you translate inside the controller for this one, unless you want to pass element and minlength to the template.

Firstly you'll need inject $translate into your controller. Then to generate your message:

this.errorMessage = $translate('MINLENGTH', { element: element, value: minlength });

This method is also outlined here.

To do this in the template (outlined here):

{{ MINLENGTH | translate : { element: element, value: minlength } }}

Solution 2 - Javascript

For anyone wondering how the syntax is, for using methods to retrieve the input for translation, this worked for me:

   {{ MINLENGTH | translate : { x: table.getShownCount(), y: table.getTotalCount() } }} 

Solution 3 - Javascript

You can also do this in the template like this.

<span data-translate="MINLENGTH" data-translate-values="{ element: element, value: minlength }"></span>

Solution 4 - Javascript

You can also use $translate.instant('MINLENGTH', { element: element, value: minlength })

Solution 5 - Javascript

This worked fine for me:

{{'commisionMessage' | translate : {fee:fee} }}|

Json File

"commisionMessage": "BLA {{fee}} BLA BLA"

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser2678324View Question on Stackoverflow
Solution 1 - JavascriptAnkhView Answer on Stackoverflow
Solution 2 - JavascriptBilleView Answer on Stackoverflow
Solution 3 - JavascriptSachindraView Answer on Stackoverflow
Solution 4 - JavascriptSamdeeshView Answer on Stackoverflow
Solution 5 - JavascriptOffirView Answer on Stackoverflow