AndreFontaine AndreFontaine - 9 days ago 6
AngularJS Question

How to load Angular translate with external modules loaded with oclazyload?

I'm working with oclazyload for the load by demand of external modules and I need to translate the content, so I'm using

angular-translate
but the translation does not work because the code that adds the part is within the controller that is loaded asynchronously.

angular
.module('main')
.controller('invoicesCtrl', invoicesCtrl);

function invoicesCtrl($scope, $translatePartialLoader, $translate) {

$translatePartialLoader.addPart('invoices');
$translate.refresh();
...

}


The main app loads the translations here:

(function () {

angular.module('main', [
'ui.router', // Angular flexible routing
'oc.lazyLoad',
'ngResource',
'pascalprecht.translate' // Angular-translate
]);

angular.module('main').config(function ($translateProvider, $translatePartialLoaderProvider) {

$translateProvider.useLoader('$translatePartialLoader', {
urlTemplate: './i18n/{part}/{lang}.json'
});

$translateProvider.preferredLanguage('en_US');
$translateProvider.forceAsyncReload(true);
$translatePartialLoaderProvider.addPart('secure');

// Enable escaping of HTML
$translateProvider.useSanitizeValueStrategy('escape');

});

})();


And for the lazy load for
invoicesCtrl
and other controllers I use (this is working fine):

function configState($stateProvider, $urlRouterProvider, $compileProvider) {
function resolveUrl(path){
var loadUrl = { // Any property in resolve should return a promise and is executed before the view is loaded
loadModule: ['$ocLazyLoad', function($ocLazyLoad) {
// you can lazy load files for an existing module
return $ocLazyLoad.load(path);
}]
};
return loadUrl;
}
}


I need to load this
addPart
before the controller itself.

$translatePartialLoader.addPart('invoices');
$translate.refresh();


Maybe an approximation can be to use an event but I'm new in javascript and I do not know how to implement it.

Answer

I solved using in the main app controllert a new function called when the link in the navigation is clicked:

<li ng-class="active" ng-click="getModuleLang('invoices')">

main.js file:

angular
    .module('main')
    .controller('appCtrl', appCtrl);

function appCtrl($scope, $translate, $translatePartialLoader) {

    // Secure translate module added to language lazy load
    $translatePartialLoader.addPart('secure');
    $translate.refresh();

    // Function that changes the language based on the headers language buttons
    $scope.changeLanguage = function (langKey) {
        $translate.use(langKey);
    };

    // Load the language modula based on the navigation element clicked
    $scope.getModuleLang = function(module){
        $translatePartialLoader.addPart(module);
        $translate.refresh();       
    }
};