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

I work with AngularJS and the integrated jQuery library in my project.

I am using the jQuery $.each() function to scroll $.each() my class. I want to create an array of objects from it, as in the following format:

 [ {"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 is that I get the same values ​​for all json objects inside the array. It seems that only the last input values ​​are created as an object, and it pushes it to the array 5 times.

+5
source share
1 answer

The problem is that after each iteration of the outer loop, you need to reset the object that you add back to the empty state. Try the following:

 $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); } 
+3
source

Source: https://habr.com/ru/post/1261639/


All Articles