SKYnine
SKYnine

Reputation: 2708

For/in loop not working in service function AngularJS

I have a problem with a for/in inside a function that does not work.

$scope.files = [];

jobslisting.getJobs(function(data){

     for(var i = 0; i < data.length; i++){
         $scope.files.push({name:data[i]});
     }

     console.log(data);        
     console.log($scope.files);

});

console.log(data) returns:

Object {2: "item1", 3: "item2", 4: "item3", 5: "item4", 6: "item5", 7: "item6", 8: "item7", 9: "item8"}

console.log($scope.files) returns

[]

Thanks in advance for any advices!

Upvotes: 0

Views: 2325

Answers (2)

Ruslan
Ruslan

Reputation: 2799

The issue is that your for loop never runs, because you are calling .length on an object and not on an array.

Instead, replace your for loop with angular.forEach(), like this:

angular.forEach(data, function(val, key) {
    $scope.files.push({name: val});
});

More info: https://docs.angularjs.org/api/ng/function/angular.forEach

Upvotes: 1

wjohnsto
wjohnsto

Reputation: 4463

It looks like data is not an Array, but an object with numbers as the keys. I would check to make absolutely sure wherever you call the service from is sending in an Array. It might also be wise to use an iterator method for data, so it will work with arrays or objects. For that you can roll your own method, or use one that is built into underscore or lodash.

Upvotes: 1

Related Questions