我一直在使用AngularJS并在我的项目中集成了JQuery库。
我正在使用JQuery的public class Bicycle {
int cadence = 0;
int speed = 0;
int gear = 1;
void changeCadence(int newValue) {
cadence = newValue;
}
void changeGear(int newValue) {
gear = newValue;
}
void speedUp(int increment) { speed = speed + increment; }
void applyBrakes(int decrement) { speed = speed - decrement;}
void printStates() {
System.out.println("cadence:" + cadence + " speed:" + speed + " gear:" + gear);
}
void vehicleType() {
System.out.println("Vehicle Type: Bicycle");
}
}
class BicycleDemo {
public static void main(String[] args) {
Bicycle bike1 = new Bicycle();
Bicycle bike2 = new Bicycle();
bike1.changeCadence(50);
bike1.applyBrakes(0);
bike1.changeGear(1);
bike1.printStates();
bike2.changeCadence(50);
bike2.speedUp(10);
bike2.changeGear(2);
bike2.changeCadence(40);
bike2.speedUp(20);
bike2.changeGear(4);
bike2.printStates();
}
}
函数来遍历我的课程。
我想用它创建一个对象数组,就像下面的格式一样:
$.each()
HTML
[
{"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"},
]
JS控制器
<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>
这里的主要问题是我为数组中的所有json对象获取相同的值。似乎只有最后一个输入值被创建为一个对象,并且它将它推送到数组5次。
答案 0 :(得分:3)
问题是因为您需要在外循环的每次迭代后重置您追加到空状态的对象。试试这个:
$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);
}