Home How to refactor my angularjs function with if validations and 2 foreach loops
Reply: 0

How to refactor my angularjs function with if validations and 2 foreach loops

user1611 Published in March 18, 2018, 2:05 am

I've written this function in order to loop through some files and their children items depending on certain criteria. Depending on what the criteria is for the file, it will return true or false.

I've made a variable validFile to keep track of the return value.

I feel like there is a cleaner way to make the function more fluid....if someone can give me some pointers on how i can make this function more simple that'd be great.

function checkFile() {
    // track file validity value
    var validFile;

    // check to see if files exists
    if($scope.files.length) {
      angular.forEach($scope.files, function(file) {
         // check to see that file has a child item
         if(file.item && file.item.child.length > 1) {
          angular.forEach(file.item.child, function(item) { 
            if(item.child.code === 8) {
              validFile = true;
        } else {
          validFile = false;

    } else {
      validFile = false;

    return validFile;

PS. the function works fine....just want to clean it up and refactor it to be neater


example of files goes something like this...

 $scope.files = [{
      length: 1,
      type: pdf,
      item: {
           type: pdf,
           code: 8

The validFile will be true if

  • $scope.files and file.item.child exists

  • item.child.code has a value of 8


You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.298693 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO