4
\$\begingroup\$

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.

\$\endgroup\$
4
\$\begingroup\$

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) {
\$\endgroup\$
1
\$\begingroup\$

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;
  };
});
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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