Search Posts

How to postpone angular expression evaluation after an asynchronous operation in Angular 1?

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>

Source: AngularJS

Leave a Reply

Your email address will not be published. Required fields are marked *