Reputation: 2708
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
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
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