I have the following function which creates an array of objects inside models
, however when I come to use models
further down the app I'm unable to loop through it's contents to pull out data.
Every loop method I've tried so far containing a single console.log()
message just prints out the message once message when models
will contain two objects so I think the problem actually lies with the creation of models
. If I create a promise and print out the value of models.devices
when it's finished processing an empty array is returned.
Any ideas?
var d = devices.split(','),
count = 0,
models = {devices:[]};
angular.forEach(d, function (device, i) {
var index = i;
if (index <= 1) {
var deviceName = device.replace(/ /g,"+").toLowerCase(),
req = '?__url_path_param=' + deviceName;
$http
.get('/api/cheapest_by_name' + req)
.success(function (obj) {
models.devices.push(obj.device);
count++;
});
}
});
$q.all(models).then(function (data) {
apiDeal.multi(data, 3, 2);
});
Then... (in api-deal.factory.js)
function apiDeal($http, $rootScope) {
return {
multi: function (devices, limit, type) {
console.log(devices); // equal to below image
console.log(devices.devices); // equal to '[]'
}
}
}
I then need to loop through devices
in apiDeal.multi
models.devices
is blank or undefined$http.success ...
models
to be a global variable (also worth looking why, maybe you should place it in a service). Try defining it withoutvar
, you might be having scope issues. It's hard to tell just by the above code.