2

When I am trying to add the usersData object to the filter idToName inside the for loop, it suddenly becomes undefined. Shouldn't the usersData get the value before the for loop runs? How should I fix it?

  Project.getProjects()
  .success(function(data) {
    vm.projects = data;
    var projectLength = vm.projects.length;

    // Get usersData
    User.allUsers()
    .success(function(data) {
      usersData = data;
      console.log(usersData); // It prints the object
    })

    for (var i = 0; i < projectLength; i++){
      console.log(usersData); // It prints undefined
      vm.projects[i].assigneeID = $filter('idToName')(vm.projects[i].assigneeID, usersData);
    }
  })
thousight
  • 1,134
  • 1
  • 14
  • 39

2 Answers2

3

It must be due to async calls. Try updating your code to following

// Get usersData
    User.allUsers()
    .success(function(data) {
      usersData = data;
      console.log(usersData); // It prints the object
      for (var i = 0; i < projectLength; i++){
          console.log(usersData); // It prints undefined
           vm.projects[i].assigneeID = $filter('idToName')(vm.projects[i].assigneeID, usersData);
      } 
    })
Nikhil Aggarwal
  • 28,197
  • 4
  • 43
  • 59
2

Move the for loop to inside the callback for the User.allUsers call. You're consuming the usersData before object is returned!

Nikhil Aggarwal
  • 28,197
  • 4
  • 43
  • 59
Michael Tang
  • 4,686
  • 5
  • 25
  • 24
  • 'Consuming the object' is a pretty inaccurate and confusing thing to say about a variable scope issue. – pvg Aug 13 '15 at 17:19
  • It's more of a (deterministic) race condition than a scoping issue. As far as we can tell, `usersData` is scoped globally. – Michael Tang Aug 13 '15 at 17:21