用于翻译的地图组合框选项

Map combobox options for translation

我的数据模型中有一堆状态名称,我想映射到不同的键进行翻译,例如

目前我的组合框是这样填充的:

<select class="form-control select" id="client"
  ng-model="statusType"
  ng-change="setStatusType(statusType)"
  ng-options="statusType.name for statusType in statusTypes track by statusType.id">
  <option value="">-</option>
</select>

我读到我可以通过这样做来实现翻译:

  ng-options="statusType.name | translate for statusType in statusTypes track by statusType.id">

但是,这将假设我的翻译键等于州名。我宁愿将我的州名映射到上面提到的翻译键。

如何在 Angular 中实现此机制?我可能需要某种自定义指令(?)。我是 Angular 的新手,欢迎所有提示。

我在想类似的东西:

mapStateToTranslationKey(statusType.name) -> return "status_" + toLowerCase(replaceSpacesWithUnderscores(statusType.name))

据此 link、https://angular-translate.github.io/docs/#/guide,我的假设是 Angular 不翻译任何内容,您需要编写代码告诉 Angular "hey, when you see this word, translate it into this word."

您可能期望的功能并不存在。我认为在翻译函数中,您需要在 Javascript 中编写,使用 Angular 函数“.translations()”,您需要显式翻译名称和密钥。而且,return 您期望的单个值。

我自己设法解决了这个问题。基本上,我必须将此功能添加到我的控制器中:

$scope.mapStateToTranslationKey = function(stateName) {
   return "state_" + stateName.toLowerCase().split(' ').join('_');
};

此函数会将州名称转换为小写,将所有空格替换为下划线,最后添加字符串 state_。最终,它 returns 一个密钥,我可以使用 angular-translate.

进行翻译

在视图中,我现在必须先调用我的函数,然后在管道符号后使用 translate 关键字。这样将使用翻译密钥而不是实际的状态名称。

<select class="form-control select" id="client"
   ng-model="statusType"
   ng-change="setStatusType(statusType)"
   ng-options="mapStateToTranslationKey(statusType.name) | translate for statusType in statusTypes track by statusType.id">
  <option value="">-</option>
</select>