24

I want to iterate through $scope variables with a for loop like this. In this example the $scope object includes an object accounts inlcuding 5 objects, whose names are numbers from 1 to 5. Each of them has a name.

for(var i = 1; i < 5; i++){
   $('#name').val($scope.accounts.i.name);
}

The problem: $scope.accounts.i is undefined because i does not count as a varibale inside the $scope variable. It counts as the letter i, so I see no chance to iterate through a scope with a for loop. When I use " " around the $scope variable it will just be displayed as plain html and angular is not interpreted.

3
  • 1
    so account is a array containing 5 objects of five key value pairs? Commented Jun 26, 2013 at 17:40
  • accounts is an array with 5 objects and several key value pairs. But of course every account has the same number of pairs. ;) Commented Jun 26, 2013 at 17:51
  • possible duplicate of Loop through array in JavaScript Commented Jun 26, 2013 at 17:55

2 Answers 2

45

Angular way to do above is

 $scope.accounts=[{name:"123"},{name:"124"},{name:"125"}]

            angular.forEach($scope.accounts,function(value,index){
                alert(value.name);
            })
Sign up to request clarification or add additional context in comments.

Comments

1

If accounts is an array, you can use the array indexer:

for(var i = 1; i < 5; i++){
   $('#name').val($scope.accounts[i].name);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.