Neil
Neil

Reputation: 2519

AngularJS: Best way to handle language file

I have a bunch of static content, labels, error messages, I want to get this out of the application as they are currently hard coded. What is the best practice for doing so?

I don't need a full i8n solution, just a single language file that is easier to edit than hard coding it into the application.

Upvotes: 2

Views: 112

Answers (1)

moribvndvs
moribvndvs

Reputation: 42497

There is a separate module called angular-translate that lets you define localizable strings and a filter to retrieve the correct string from the current locale to display in your view. I'm not sure what you mean by "single language file", but this supports entering strings in your config via a table or loading the strings for a locale from a file.

Simple example from the guide (loading strings from a table):

var app = angular.module('myApp', ['pascalprecht.translate']);
app.config(['$translateProvider', function ($translateProvider) {
  $translateProvider.translations('en', {
    'TITLE': 'Hello',
    'FOO': 'This is a paragraph',
  });

  $translateProvider.translations('de', {
    'TITLE': 'Hallo',
    'FOO': 'Dies ist ein Paragraph'
  });

  $translateProvider.preferredLanguage('en');
}]);

In your view, just use the filter syntax:

<h1>{{ 'TITLE' | translate }}</h1>
<p>{{ 'FOO' | translate }}</p>

Upvotes: 2

Related Questions