控制器中角度平移的正确使用 [英] Correct use for angular-translate in controllers
问题描述
我在 AngularJS 应用程序中为 i18n 使用 angular-translate.
I'm using angular-translate for i18n in an AngularJS application.
对于每个应用程序视图,都有一个专用控制器.在下面的控制器中,我将值设置为显示为页面标题.
For every application view, there is a dedicated controller. In the controllers below, I set the value to be shown as the page title.
<h1>{{ pageTitle }}</h1>
JavaScript
.controller('FirstPageCtrl', ['$scope', '$filter', function ($scope, $filter) {
$scope.pageTitle = $filter('translate')('HELLO_WORLD');
}])
.controller('SecondPageCtrl', ['$scope', '$filter', function ($scope, $filter) {
$scope.pageTitle = 'Second page title';
}])
我正在使用 angular-translate-loader-url 加载翻译文件 扩展名.
I'm loading the translation files using the angular-translate-loader-url extension.
在初始页面加载时,会显示翻译键而不是该键的翻译.翻译是Hello, World!
,但我看到的是HELLO_WORLD
.
On the initial page load, the translation key is shown instead of the translation for that key. The translation is Hello, World!
, but I'm seeing HELLO_WORLD
.
第二次访问该页面时,一切正常,并显示了翻译版本.
The second time I go to the page, all is well and the translated version is shown.
我认为问题与以下事实有关:当控制器将值分配给 $scope.pageTitle
时,翻译文件可能尚未加载.
I assume the issue has to do with the fact that maybe the translation file is not yet loaded when the controller is assigning the value to $scope.pageTitle
.
当使用
和 {{ pageTitle |翻译}}</h1>
$scope.pageTitle = 'HELLO_WORLD';
,翻译从第一次开始就完美了.这样做的问题是我并不总是想使用翻译(例如,对于第二个控制器,我只想传递一个原始字符串).
When using <h1>{{ pageTitle | translate }}</h1>
and $scope.pageTitle = 'HELLO_WORLD';
, the translation works perfect from the first time. The problem with this is that I don't always want to use translations (eg. for the second controller I just want to pass a raw string).
这是已知问题/限制吗?怎么解决?
Is this a known issue / limitation? How can this be solved?
推荐答案
EDIT:请参阅 PascalPrecht(angular-translate 的作者)的答案以获得更好的解决方案.
EDIT: Please see the answer from PascalPrecht (the author of angular-translate) for a better solution.
加载的异步特性导致了这个问题.你看,用 {{ pageTitle |翻译}}
,Angular 会观察表达式;加载本地化数据后,表达式的值会发生变化并更新屏幕.
The asynchronous nature of the loading causes the problem. You see, with {{ pageTitle | translate }}
, Angular will watch the expression; when the localization data is loaded, the value of the expression changes and the screen is updated.
所以,你可以自己做:
.controller('FirstPageCtrl', ['$scope', '$filter', function ($scope, $filter) {
$scope.$watch(
function() { return $filter('translate')('HELLO_WORLD'); },
function(newval) { $scope.pageTitle = newval; }
);
});
但是,这将在每个摘要循环中运行被监视的表达式.这是次优的,可能会也可能不会导致明显的性能下降.无论如何,这是 Angular 所做的,所以它不会那么糟糕......
However, this will run the watched expression on every digest cycle. This is suboptimal and may or may not cause a visible performance degradation. Anyway it is what Angular does, so it cant be that bad...
这篇关于控制器中角度平移的正确使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!