Reputation: 2146
I am trying to build an array of object using AngularJS.
Fisrt I start with only 1 object. When the user click on a button it add a object to my array.
This is the button part that is working;
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.
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
. Everytime the button is pressed a new object is created inside the array row
.
I am displaying the row
array on my page to see the changes and I do it like this:
HTML:
row = {{row}}
So before I press the button I have only one object with an id of 0; Everytime I press the button I can see the new object getting added to the array but the id is always 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.
Upvotes: 0
Views: 381
Reputation: 14423
Do it like this:
$scope.nbrForme = 0;
$scope.row = [];
$scope.ajoutForme = function(){
$scope.row.push({
id: $scope.nbrForme++
});
}
Upvotes: 2
Reputation: 16805
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
. so you pushed duplicate object that unexpected and may will show error when try to show in DOM using ng-repeat
without track by
.
Upvotes: 1