user3606027
user3606027

Reputation: 1

AngularJS $translate.refresh() not working on load

I'm testing Angular-translate with angular-traslate-partial-loader and it is not populating the page with the default translation on page load.

here is a plunkr of the problem recreated

app.controller('MainCtrl', ['$scope', '$translate', '$translatePartialLoader',
  function($scope, $translate, $translatePartialLoader) {
    $translatePartialLoader.addPart('test');
    $translate.refresh();
    $scope.dotranslate = function() {
      $translate.refresh();
    };
  }
]);

http://plnkr.co/edit/Vts9CW4VoJsXoSdllFsq?p=preview

I added a refresh button to show that the $translate.refresh() works after page load.

What am i missing?

Upvotes: 0

Views: 6795

Answers (1)

James
James

Reputation: 3239

I've never used $translate so I'm not sure exactly what the problem is, but you may be changing a value too late in the digest cycle for the refresh to catch it.

You can use $scope.$evalAsync to fix this. See the angular documentation here: https://docs.angularjs.org/api/ng/type/$rootScope.Scope

Here is an example of your app.js with the change:

var app = angular.module('plunker', ['pascalprecht.translate']);
app.config(function run($translateProvider, $translatePartialLoaderProvider) {
  $translateProvider.useLoader('$translatePartialLoader', {
    urlTemplate: 'translation-{lang}-{part}.json'
  });

  $translateProvider.preferredLanguage('fr-FR');
});
app.controller('MainCtrl', ['$scope', '$translate', '$translatePartialLoader',
  function($scope, $translate, $translatePartialLoader) {
    $translatePartialLoader.addPart('test');

    //I wrapped your refresh in the eval async function
    $scope.$evalAsync(function() {
      $translate.refresh();
    });

    $scope.dotranslate = function() {
      $translate.refresh();
    };
  }
]);

Upvotes: 3

Related Questions