0

How do I postpone the evaluation of angular expressions in the HTML after an asynchronous operation?

I need the translate function that only becomes defined after an AJAX call.

Here is the code:

angular.module('app', [])
  .run(['$rootScope', '$http', function($rootScope, $http) {
    $rootScope.locale = 'en';
    $http.get('/resources').then(response => {
      let dictionary = response.data;
      $rootScope.tr = (key, ...args) => {
        let text = dictionary[$rootScope.locale][key];
        args.forEach((value, index) => text = text.replace(`{${index}}`, value));
        return text;
      };
    });
  }

In the HTML,

<body ng-app="app"> {{tr('page.title')}} </body>
georgeawg
  • 48,608
  • 13
  • 72
  • 95
Xegara
  • 103
  • 1
  • 7
  • 18
  • 1
    It's a common problem, and you cannot 'pause' the app. One of the solutions is to postpone app bootstrapping. Another one is to use a router and route resolvers to pre-load data. – Estus Flask Nov 22 '17 at 07:01
  • 1
    Possible duplicate of https://stackoverflow.com/questions/47391797/initialize-angularjs-app-before-calling-the-controllers/47394275 – Estus Flask Nov 22 '17 at 07:01
  • do I understand it right that you are getting error because `tr()` is not declared yet? Then 1. declare function as all other components - from very beginning; 2. after loading data re-declare translation data; 3. everything else will do $digest loop for you PS. use one-time binding for translations - except template ones - they are never changed – skyboyer Nov 22 '17 at 07:08
  • If I declare the method, will it evaluate the expressions of tr() again? – Xegara Nov 22 '17 at 07:10
  • @Xegara Expressions are evaluated on each digest. $http request completion results in a digest. So yes. If you're comfortable with blank initial placeholders, it will work this way. The use of $rootScope for globals is discouraged. Things like translation are usually done via filters. You can check how it's done in existing solutions like angular-translate. – Estus Flask Nov 22 '17 at 07:18

0 Answers0