Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

I'm very new to AngularJS. I'm using a directive for translation of category objects like:

{
"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.

share|improve this question

2 Answers 2

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 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) {
share|improve this answer

You can use angular.isUndefined and angular.forEach to fine tune the code:

app.filter('categoryTranslations', function() {
  return function(categories, locale) {
    var translated = [];
    if (!angular.isUndefined(categories)) {
        angular.forEach(categories, function(category) {
            angular.forEach(category.CategoryTranslations, function(translation) {
                if (translation.Language.code == locale) {
                    category.defaultTranslation = translation;
                    translated.push(category);
                    break;
                }
            });
        });
    }
    return translated;
  };
});
share|improve this answer
1  
if (!angular.isUndefined(categories) { <-- syntax error. –  wvxvw Apr 5 at 11:50
    
@wvxvw: Thanks for notify. Typo error, corrected. –  Arulkumar Apr 5 at 13:45

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.