Javascript 如何在angular-translate中传递参数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33958340/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 15:43:22  来源:igfitidea点击:

How to pass parameters in angular-translate

javascriptangularjs

提问by Ankh

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.

我正在使用 angularjs 翻译我的错误消息。

"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.

如果我在用户名字段中输入 1 个字符,错误会说:username must be at least 5 characters.

Is what I am trying to do even possible?

我正在尝试做的甚至可能吗?

回答by Ankh

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

如果您在控制器内部为这个翻译可能是最好的,除非您想传递elementminlength到模板。

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

首先,您需要注入$translate控制器。然后生成您的消息:

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 }' }}

回答by Sachindra

You can also do this in the template like this.

您也可以像这样在模板中执行此操作。

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

回答by Samdeesh

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

你也可以使用 $translate.instant('MINLENGTH', { element: element, value: minlength })

回答by Bille

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() } }}