我曾经使用angular- translate过i18n。我想将$translatePartialLoader服务用于模块化语言密钥作为延迟加载。我也想为此使用ui- router解决选项。
angular- translate
$translatePartialLoader
ui- router
现在该怎么做?是否可以为我添加代码示例?
谢谢
我找到解决方案并解决我的问题。
在配置中:
$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索引中:
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:
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工厂:
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和trans作为参数controllers:
trans
controllers
app.controller('UserListCtrl',function($scope,...,$translatePartialLoader,trans){