leaksterrr
leaksterrr

Reputation: 4167

Angular loop through object array

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 '[]'

        }

    }

}

console.log(devices)

I then need to loop through devices in apiDeal.multi

Upvotes: 1

Views: 142

Answers (1)

Omri Aharon
Omri Aharon

Reputation: 17064

You need to keep an array of promises, which should replace the models you're using the $q.all on. It has to be an array of promises.

So change your code to this:

var d = devices.split(','),
    count = 0,
    models = {devices:[]},
    promises = [];

var promise = $http
            .get('/api/cheapest_by_name' + req)
            .success(function (obj) {
                models.devices.push(obj.device);
                count++;
            });

promises.push(promise);

And then, do:

$q.all(promises).then(function (data) {
    apiDeal.multi(data, 3, 2);
});

Simple Fiddle demonstration

Upvotes: 2

Related Questions