I'm using AngularJS and Angular Translate. I have an array of objects that have 'key' property - a string that should be translated.
This is my array of objects:
var objects = [{
id: 1,
key: 'Jacket'
}, {
id: 2,
key: 'Trousers'
}, {
id: 3,
key: 'Hat'
}];
These are my translations:
var translationsEN = {
Jacket: 'This is Jacket in English',
Trousers: 'This is Trousers in English',
Hat: 'This is Hat in English'
}
When some particular events occur I need an array of the objects but with the translations, not with the keys. That's why I have a function that does the following:
var translatedObjects = [];
for (var i = 0; i < objects.length; i++) {
$translate(objects[i].key).then(function (translation) {
translatedObjects[i] = translation;
});
}
After the function execution the result stored in the translatedObjects array is:
[null,null,null,"This is Hat in English"]
I guess that this is happening because I'm actually executing an asynchronous call to the $translate service and translatedObject[i] is not actually pointing to the right object, because 'i' is not defined in the current context.
So, how can I execute an asynchronous function call and assign my array appropriately as shown in the example above?