I want to loop over an array $scope.todos
for (var i = $scope.todos.length - 1; i >= 0; i--) {
console.log($scope.todos[i]);
};
But $scope.todos.length
returns 0
.
$scope.todos
looks like this:
What am I doing wrong? I think this is not an associative array? The indexes are numbers? It doesn't return undefined
, just 0. Thanks for any help.
Edit: more code
'use strict';
angular.module('todos')
.controller('TodosController', ['$scope', '$location', '$state', '$stateParams', 'Todos',
function($scope, $location, $state, $stateParams, Todos) {
console.log($scope.todos);
console.log($scope.todos.length);
function calculateDayAygoForTodos(){
//foreach todo in todos
for (var i = $scope.todos.length - 1; i >= 0; i--) {
console.log("todos length");
console.log($scope.todos[i]);
};
}
Solution:
The problem was the async nature of the functions, I was trying to call the $scope.todos.length
before the todos were loaded. Solved with a simple delay using timeOut
function:
setTimeout(function() {
console.log($scope.todos.length);
}, 1000);
Might not be optimal solution, but now I don't get ùndefined`anymore, but the length of the array. Thanks to War10ck for pointing this out.