[英]AngularJS Json array of object
I am trying to build an array of object using AngularJS. 我正在尝试使用AngularJS构建对象数组。
Fisrt I start with only 1 object. 首先,我仅以1个对象开始。 When the user click on a button it add a object to my array. 当用户单击按钮时,它将一个对象添加到我的数组中。
This is the button part that is working; 这是起作用的按钮部分;
HTML : HTML :
<button ng-click="ajoutForme()" type="button" class="btn btn-default">+</button>
Angular : 角度 :
$scope.ajoutForme = function(){
$scope.nbrForme++;
}
This is working as expected and I can see nbrForme incrementing on the page. 这正在按预期工作,我可以在页面上看到nbrForme递增。
But this button is actually adding a row to be filled in my table. 但是此按钮实际上是在表中添加一行。 So everytime the button is clicked I want to insert a new row to my table. 因此,每次单击按钮时,我都想在表格中插入新行。
I do the following; 我执行以下操作;
Angular : 角度 :
$scope.row = [];
$scope.$watch('nbrForme', function() {
for(i=0; i<nbrForme; i++){
$scope.row.push({
id: i
});
}
});
Since I am watching the nbrForme
. 由于我正在观看nbrForme
。 Everytime the button is pressed a new object is created inside the array row
. 每次按下按钮,都会在数组row
内创建一个新对象。
I am displaying the row
array on my page to see the changes and I do it like this: 我在页面上显示row
数组以查看更改,我这样做是这样的:
HTML : HTML :
row = {{row}} 行= {{行}}
So before I press the button I have only one object with an id of 0; 因此,在按下按钮之前,我只有一个对象,其ID为0。 Everytime I press the button I can see the new object getting added to the array but the id is always 0. 每次按下按钮,我都可以看到新对象已添加到数组中,但id始终为0。
So im getting an output that look like: 所以即时通讯输出看起来像:
row = [{"id":0},{"id":0},{"id":0},{"id":0},{"id":0}]
So I am wondering why the var i
is not being incremented. 所以我想知道为什么var i
没有增加。
Do it like this: 像这样做:
$scope.nbrForme = 0;
$scope.row = [];
$scope.ajoutForme = function(){
$scope.row.push({
id: $scope.nbrForme++
});
}
Can try it 可以尝试一下
$scope.ajoutForme = function(){
$scope.nbrForme++;
$scope.row.push({
id: $scope.nbrForme
});
}
when you used 当你使用
for(i=0; i<nbrForme; i++){
$scope.row.push({
id: i
});
}
every time starting push in row
from 0
to nbrForme
. 每次从0
到nbrForme
开始推入row
。 so you pushed duplicate object that unexpected and may will show error when try to show in DOM using ng-repeat
without track by
. 因此,您推送了意外的重复对象,当尝试使用ng-repeat
没有track by
DOM中显示时,可能会显示错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.