在控制器正确使用角翻译 [英] Correct use for angular-translate in controllers

查看:141
本文介绍了在控制器正确使用角翻译的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用角转换以国际化在AngularJS应用程序。

I'm using angular-translate for i18n in an AngularJS application.

有关每一个应用视图,还有一个专用控制器。在下面的控制器,I值设置为显示在页面的标题。

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';
    }])

我加载使用<一个翻译文件href=\"https://github.com/Pascal$p$pcht/angular-translate/wiki/Asynchronous-loading\">angular-translate-loader-url扩展。

在初始页面加载,转换键显示,而不是翻译的关键。翻译是的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.

在使用&LT; H1&GT; {{PAGETITLE |翻译}}&LT; / H1&GT; $ 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?

推荐答案

加载的异步特性导致该问题。你看,用 {{PAGETITLE |翻译}} ,角会让看表的前pression;加载定位数据时,对前pression的值更改和屏幕更新。

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.

所以,你可以做你自己:

So, you can do that yourself:

.controller('FirstPageCtrl', ['$scope', '$filter', function ($scope, $filter) {
    $scope.$watch(
        function() { return $filter('translate')('HELLO_WORLD'); },
        function(newval) { $scope.pageTitle = newval; }
    );
});

不过,这将运行在每个消化周期看前pression。这是不理想的,并且可以或可以不引起明显的性能下降。反正它是角做什么,所以不能说不好......

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆