3

I have a list of json objects, $scope.phones, and a folder full of json files with additional data about each phone. I am trying to iterate through the files to grab additional information to put in my list about each phone:

phonecatControllers.controller('PhoneListCtrl', ['$scope', 'Phone',
function($scope, Phone) {
$scope.phones = Phone.query();

var myTimer = window.setTimeout(function() {

    for (var i = 0; i < $scope.phones.length; i++){ 
        var weight = 0;             
        Phone.get({phoneId: $scope.phones[i].id}, function( phone) {
            weight = phone.sizeAndWeight.weight;
            $scope.phones[i].weight = weight;           
        });     
    };
} , 1000 );

$scope.orderProp = 'age';
}]);

The timer is so that the function doesn't run until after scope.phones is set, (I realize its a bit of a hack but its not causing issues.) I get an error cannot set property of undefined on:

$scope.phones[i].weight = weight;   

If i try to access this outside of the .get method there isn't a problem, however the new value of weight does not exist outside of the get method.

user3549700
  • 77
  • 1
  • 8
  • 3
    There are a few issues going on here, first you should look at promises to not update the phones until the phones are loaded since there is a possibility that it could take longer than 1 second to load the phones. Also, when `Phone.get` resolves i will always be `$scope.phones.length` you'll want to check out closures to fix that: http://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example – HJ05 Apr 15 '15 at 22:27

1 Answers1

1

wait for the list of phones before looping through them:

Phone.query().then(function(phones){
  for(var i=0; i<phones.length; i++){
    var weight = 0;             
    Phone.get({phoneId: phones[i].id}, function( phoneDetails) {
        weight = phoneDetails.sizeAndWeight.weight;
        phones[i].weight = weight;           
    });
  }
}
Jan Peter
  • 380
  • 6
  • 16