如何等待Angular模块加载?

时间:2014-10-28 12:40:29

标签: javascript angularjs internationalization i18next

我试图在我的Angular项目中使用i18next(https://github.com/archer96/ng-i18next),但似乎加载速度太慢。这是我的设置:

angular.module('jm.i18next').config(['$i18nextProvider', function ($i18nextProvider) {
    $i18nextProvider.options = {
        lng: 'en',
        fallbackLng: 'en',
        preload: ['en'],
        supportedLngs: ['en'],
        resGetPath: '../locales/__lng__.json',
        useCookie: false,
        useLocalStorage: false,
        defaultLoadingValue: ''
    };
}]);

angular.module('myApp', ['jm.i18next']).controller('MainCtrl', ['$scope', '$i18next', function ($scope, $i18next) {
console.log($i18next("key"));

setTimeout(function() {
    console.log($i18next("key"));
  }, 1000);
}]);

我必须添加超时才能获得值。有没有办法确保在加载控制器时i18next准备就绪?


更新

我尝试按类型对锻炼进行分组,使用$ i18next进行翻译。但这不起作用,因为视图已经准备好了#34;在控制器完成翻译之前。

<select ng-model="workout" ng-options="workout as workout.name group by workout.type for workout in workouts | orderBy: ['type', 'name']"></select>

$scope.workouts = [
    {id: 1, name: 'Workout 1', type: $i18next("type1")},
    {id: 25, name: 'Workout 2', type: $i18next("type2")},
  ];

2 个答案:

答案 0 :(得分:1)

这解决了我的问题。

angular.module('myApp', ['ngRoute', 'jm.i18next']).
        config(['$routeProvider', function ($routeProvider) {
            $routeProvider.
                when('/route1', {
                    title: 'Route 1',
                    templateUrl: '../views/route1.html',
                    controller: 'Route1Ctrl',
                    resolve: {
                      i18next: function ($i18next) {
                        return $i18next;
                      }
                    }
                });
    }]);

答案 1 :(得分:0)

您还可以收听i18nextLanguageChange事件:

$scope.$on('i18nextLanguageChange', function () {
  $scope.workouts = [
    {id: 1, name: 'Workout 1', type: $i18next("type1")},
    {id: 25, name: 'Workout 2', type: $i18next("type2")},
  ];
});

你必须以自己的方式解决其他竞争条件。