简体   繁体   English

角度遍历对象数组

[英]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. 我具有以下在models内部创建对象数组的函数,但是当我进一步在应用程序中使用models时,无法循环浏览其内容以提取数据。

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 . 到目前为止,我尝试过的每个循环方法都包含一个console.log()消息,当models包含两个对象时,该消息只会打印出一次消息,因此我认为问题实际上出在models的创建上。 If I create a promise and print out the value of models.devices when it's finished processing an empty array is returned. 如果我创建一个promise并在完成处理后打印出models.devices的值,则返回一个空数组。

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) 然后...(在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(装置)

I then need to loop through devices in apiDeal.multi 然后,我需要遍历apiDeal.multi devices

You need to keep an array of promises, which should replace the models you're using the $q.all on. 您需要保留一个诺言数组,该诺言应替换您使用$q.allmodels 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 简单的小提琴示范

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM