Correct use for angular-translate in controllers

后端 未结 5 1703
野的像风
野的像风 2020-11-27 09:45

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 v

5条回答
  •  南笙
    南笙 (楼主)
    2020-11-27 10:13

    To make a translation in the controller you could use $translate service:

    $translate(['COMMON.SI', 'COMMON.NO']).then(function (translations) {
        vm.si = translations['COMMON.SI'];
        vm.no = translations['COMMON.NO'];
    });
    

    That statement only does the translation on controller activation but it doesn't detect the runtime change in language. In order to achieve that behavior, you could listen the $rootScope event: $translateChangeSuccess and do the same translation there:

        $rootScope.$on('$translateChangeSuccess', function () {
            $translate(['COMMON.SI', 'COMMON.NO']).then(function (translations) {
                vm.si = translations['COMMON.SI'];
                vm.no = translations['COMMON.NO'];
            });
        });
    

    Of course, you could encapsulate the $translateservice in a method and call it in the controller and in the $translateChangeSucesslistener.

提交回复
热议问题