0

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.

3
  • 2
    Why don't you just push it inside the ajoutForme function?
    – MinusFour
    Commented Mar 12, 2016 at 19:40
  • Even if I do that 'i' is not being incremented Commented Mar 12, 2016 at 19:43
  • But it is working if I use nbrForme and drop the loop Commented Mar 12, 2016 at 19:45

2 Answers 2

2

Do it like this:

$scope.nbrForme = 0;
$scope.row = [];
$scope.ajoutForme = function(){
    $scope.row.push({
        id: $scope.nbrForme++
    });
}
1
  • @Abhishek, your demo made me realize that i was missing $scope thanks.
    – MinusFour
    Commented Mar 12, 2016 at 20:05
1

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.