如何在使用ui-router resolve显示任何UI之前加载Angular-translate

时间:2016-05-16 05:11:10

标签: angularjs angular-ui-router angular-translate resolve

我将angular-translate用于i18n。我想将$translatePartialLoader服务用于模块化语言密钥作为延迟加载。另外,我想为此使用ui-router解析选项。

现在怎么做?可以为我添加一个代码示例吗?

由于

1 个答案:

答案 0 :(得分:4)

我找到了解决方案并解决了我的问题。

在配置中:

$translatePartialLoaderProvider.addPart('index');
        $translateProvider
            .useSanitizeValueStrategy(null)
            .fallbackLanguage('en-us')
            .registerAvailableLanguageKeys(['en-us','pt-br'], {
                'en_*': 'en-us',
                'pt_*': 'pt-br'
            })
            .useLoader('$translatePartialLoader', {
                urlTemplate: '{part}/locale_{lang}.json'
            })
            .useLoaderCache(true)
            .useCookieStorage()
            .determinePreferredLanguage();

ui-router索引中:

.state('index', {
    url: '/index',
    templateUrl: 'index.html',                   
    controller:'IndexCtrl',
    resolve: {
        trans:['RequireTranslations',
            function (RequireTranslations) {
                RequireTranslations('index');
            }],
        dep: ['trans','$ocLazyLoad',
            function(trans,$ocLazyLoad){
                return $ocLazyLoad.load(['plugin']).then(
                    function(){
                        return $ocLazyLoad.load(['IndexCtrl.js']);
                    }
                );
            }]
    }
})
.state('index.users',{
    url: "/users",
    templateUrl: "users.html",
    controller:'UserListCtrl',
    resolve: {
        trans:['RequireTranslations',
            function (RequireTranslations) {
                RequireTranslations('modules/user');
            }],
        dep: ['trans','$ocLazyLoad',
            function(trans,$ocLazyLoad){
                return $ocLazyLoad.load(['UserListCtrl.js'])
            }]

    }
})

run

app.run(function($rootScope,$translate) {

    // translate refresh is necessary to load translate table
    $rootScope.$on('$translatePartialLoaderStructureChanged', function () {
        $translate.refresh();
    });

    $rootScope.$on('$translateChangeEnd', function() {
        // get current language
        $rootScope.currentLanguage = $translate.use();
    });
})

并在RequireTranslations工厂中:

app.factory('RequireTranslations', function($translatePartialLoader, $translate,$rootScope) {
    return function() {
        angular.forEach(arguments, function(translationKey) {
            $translatePartialLoader.addPart(translationKey);
        });
        return $translate.refresh().then(
            function(){
                return $translate.use($rootScope.currentLanguage);
            }
        );
    };
});

请注意,您应在所有$translatePartialLoader中添加transcontrollers作为参数,如下所示:

app.controller('UserListCtrl',function($scope,...,$translatePartialLoader,trans){