How to pass parameters in angular-translate
JavascriptAngularjsJavascript 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"