Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS and JQuery $.each() function only returns the last loop value

I've been working with AngularJS and integrated JQuery library in my project.

I am using JQuery's $.each() function to loop through my class. I want to create an array of objects out of it just like the format below:

[
    {"invoice_no":"value1", "brand":"value2", "model":"value3"},
    {"invoice_no":"value1", "brand":"value2", "model":"value3"},
    {"invoice_no":"value1", "brand":"value2", "model":"value3"},
    {"invoice_no":"value1", "brand":"value2", "model":"value3"},
    {"invoice_no":"value1", "brand":"value2", "model":"value3"},
]

HTML

<div class="panels">
   <input class="form-control" name="invoice_no">
   <input class="form-control" name="brand">
   <input class="form-control" name="model">
</div>
<div class="panels">
   <input class="form-control" name="invoice_no">
   <input class="form-control" name="brand">
   <input class="form-control" name="model">
</div>
<div class="panels">
   <input class="form-control" name="invoice_no">
   <input class="form-control" name="brand">
   <input class="form-control" name="model">
</div>
<div class="panels">
   <input class="form-control" name="invoice_no">
   <input class="form-control" name="brand">
   <input class="form-control" name="model">
</div>
<div class="panels">
   <input class="form-control" name="invoice_no">
   <input class="form-control" name="brand">
   <input class="form-control" name="model">
</div>

JS Controller

$scope.saveData = function(){
    var arrayOFProducts = [];
    var object =  {};

    angular.element('.panels').each(function(){
            $(this).find('.form-control').each(function(){
                var key = $(this).attr('name');
                var value = $(this).val();
                object [key] = value;   
            });
            arrayOFProducts.push(object);
    });

    console.log(arrayOFProducts);

}

The main problem here is that I get the same values for all the json objects inside the array. It seems that only the last input values are being created as an object and the it pushes it to the array 5 times..

like image 731
Kim Carlo Avatar asked Oct 18 '22 20:10

Kim Carlo


1 Answers

The issue is because you need to reset the object you append back to an empty state after each iteration of the outer loop. Try this:

$scope.saveData = function() {
    var arrayOFProducts = [];

    angular.element('.panels').each(function() {
        var obj =  {}; // note this moved to here

        $(this).find('.form-control').each(function() {
            var key = $(this).attr('name');
            var value = this.value;
            obj[key] = value;
        });
        arrayOFProducts.push(object);
    });

    console.log(arrayOFProducts);
}
like image 180
Rory McCrossan Avatar answered Oct 20 '22 10:10

Rory McCrossan