angularjs - 通过将文本作为键传递来使用角度翻译
问题描述
我的应用程序在 angularJs 上。我是角度翻译的新手。经历了几个例子,比如http://angular-translate.github.io/。每个场景我都需要定义两种语言文本(例如:如果我需要将“标题”更改为英语到德语,我需要以两种语言定义标题 $translateProvider.translations('en') $translateProvider.translations('de' ) ) 这是翻译 angularJs 应用程序的唯一方法吗?有什么方法可以将文本作为键传递并根据选择的语言进行翻译而不定义两个文本?
以这种方式尝试但没有奏效。
$rootScope.$on('$translateChangeSuccess', function () {
$translateProvider.preferredLanguage('fa');
$scope.pageTitle = $translate.instant('Title');
});
在视图中:
{{页面标题}}
我能知道更改文本的更好方法吗?
解决方案
不,这是不允许的。您需要为您支持的所有语言指定文本。正如您正确分享了 angular-translate 文档的 url - http://angular-translate.github.io/。您需要确保一种语言的所有键和文本也存在于您支持的其他语言中。否则,它可能会导致 UI 出现错误,其中字符串文字显示为 {{ title }},这并不好。
我还建议您通过指定fallbackLanguage 和preferredLanguage 来定义您的备用语言。
如果您有一些来自后端的类似枚举的值,并且这些值没有在后端翻译,我建议您在翻译中为这些枚举添加键并在运行时使用它(就像我在上面分享的那样)。
您还可以使用用户输入的数据并将其与本地化文本连接,如下所示:
//Let's say $scope.name is the name of the user.
$translate.instant('welcome_msg', [$scope.name]);
//String literal in your translation will have {0} and name will be populated at
//this place at runtime.
'welcome_msg' : 'Welcome {0}'
推荐阅读
- android - 如何在 Kotlin 中调用另一个活动的方法?
- r - 将因素放在数据框R中
- sql - GCP Bigquery 中的动态合并
- sql - 如何将此 SQL 查询转换为 JOIN?
- python - 在 google colab 中使用 [print(n) for n in list]
- javascript - TypeScript 数组定义
- python-3.x - @lru_cache 在具有交换参数的函数上
- postgresql - typeorm 不适用于软删除记录和唯一约束字段
- mysql - MySQL插入成功执行并返回ID,但有时并发时不保存数据
- python - Tkinter 在使用自定义图像背景时删除小部件背景