Joseph McCarthy Joseph McCarthy - 1 year ago 131
AngularJS Question

How to iterate through an internationalised JSON array using i18next and Angular

I have a series of json internationalization files with basic strings, arrays of strings and arrays of json objects, and I've been trying to display in angular them using various i18n libraries.
The en_GB file is below

"key": "value en_GB",
"headings": ["header1 en_GB", "header2 en_GB", "header3 en_GB"],
"objects": [
{"title": "title1 en_GB", "subject": "subject1 en_GB"},
{"title": "title2 en_GB", "subject": "subject2 en_GB"},
{"title": "title3 en_GB", "subject": "subject3 en_GB"}

I've tried angular-translate - - but it doesn't support arrays. The workaround is to return a string, separated by a delimiter, and then call split() on that string. However, it doesn't support returning JSON objects at all

Currently I'm examining ng-i18next - - an angular module that uses the i18next library, and it's pretty close to what I need.

String arrays are delimited by newline characters - "\n" - so I've split on that character to iterate through an array, but I'm still having the same problem with JSON objects arrays. I can display specific indexes in the array with an index - e.g. objects.0.title, but I can't iterate using ng-repeat.

I've set up a plunker here that demonstrates this -
Can anyone suggest a way to iterate through the objects in the "objects" array?

Answer Source

I solved this using angular-translate with a similar solution to the "Load Static Files" demo in the codebase -

I converted the objects array converted to

  "key": "value en_GB",
    "headings": ["header1 en_GB", "header2 en_GB", "header3 en_GB"],
    "objects": {
        "one": {"title": "title1 en_GB", "subject": "subject1 en_GB"},
        "two": {"title": "title2 en_GB", "subject": "subject2 en_GB"},
        "three": {"title": "title3 en_GB", "subject": "subject3 en_GB"}

In the controller I've added the keys to an array, and the assigned their translations to an array in $scope, which I can iterate through using ng-repeat in the partial HTML file

var keys = ["one", "two", "three"];
$scope.objects = []
angular.forEach(keys, function(value, key) {
    var object = {};
    $translate("objects." + key + ".title").then(function(translation) {
         object.title = translation;
    $translate("objects." + key + ".subject").then(function(translation) {
         object.subject = translation;
}, $scope.objects);

<div ng-repeat="object in objects">{{object.title}} {{object.subject}}</div>

The downside of this is that any new JSON objects I add to the "objects" array isn't picked up automatically, its attribute name has to be added to the "keys" array to display it on screen.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download