snippetjavascriptMinor
AngularJS Translation Filter
Viewed 0 times
angularjstranslationfilter
Problem
I'm very new to AngularJS. I'm using a directive for translation of category objects like:
Filter:
I really don't like the code and am looking for a better way to solve this problem.
{
"id":17,
"order":2,
"published":false,
"createdAt":"2014-12-29T16:22:43.000Z",
"updatedAt":"2014-12-29T16:23:22.000Z",
"CategoryTranslations":[
{
"id":13,
"name":"Fishes",
"description":"Fishes desc",
"CategoryId":17,
"LanguageId":1,
"Language":{
"id":1,
"code":"en_EN",
"name":"English"
}
}
]
}Filter:
app.filter('categoryTranslations', function() {
return function(categories, locale) {
var translated = [];
if (typeof categories != 'undefined') {
for (var i = 0; i < categories.length; i++) {
var category = categories[i];
for (var j = 0; j < category.CategoryTranslations.length; j++) {
var translation = category.CategoryTranslations[j];
if (translation.Language.code == locale) {
category.defaultTranslation = translation;
translated.push(category);
break;
}
}
}
}
return translated;
};
});I really don't like the code and am looking for a better way to solve this problem.
Solution
I don't know much about angular.js myself, but I can give some small tips about your code.
Indentation
Code, in general, looks ugly without proper indentation.
I recommend that you indent the body of the second parameter passed into
Why are you checking with 'undefined'?
On the line that goes:
Why are you comparing with
If you want to check is categories was defined, you could just do
Indentation
Code, in general, looks ugly without proper indentation.
I recommend that you indent the body of the second parameter passed into
app.filter.Why are you checking with 'undefined'?
On the line that goes:
if (typeof categories != 'undefined') {Why are you comparing with
'undefined'?If you want to check is categories was defined, you could just do
if (categories) {Code Snippets
if (typeof categories != 'undefined') {if (categories) {Context
StackExchange Code Review Q#75442, answer score: 4
Revisions (0)
No revisions yet.