J. Davidson
J. Davidson

Reputation: 3307

Angularjs adding row at curent row location

I have following code that is suppose to add another row at current row location (not at the bottom of the rows):

<tr ng-repeat="ro in rows">
  <td>{{ro.name}}</td>
  <td>{{ro.id}}</td>
  <td><a ng-click="addRo($index)">add row</a></td>
</tr>

In my controller, I have:

$scope.addRo=function(index){
     $scope.inderted={
       id: '',
       name: ''
      };
      $scope.rows($index+1).push($scope.inserted);
}

I tried the above code hopeing adding index to the current location it would add it, but it doesn't work. How to fix this?

Upvotes: 1

Views: 375

Answers (3)

ryanyuyu
ryanyuyu

Reputation: 6486

Since you have access to the $index of the current element within the ng-repeat, inserting a new row is easy. The problem with your current code is that array.push always adds the element to the end of the array.

Use array.splice to actually insert elements into the array.

$scope.addRo = function(index) {
        var newObj = {
            id: '',
            name: ''
        };
        $scope.rows.splice(index + 1, 0, newObj); //inserts a row after this one
                                                  //use index for a new row here
    };

Upvotes: 0

Rorschach120
Rorschach120

Reputation: 1210

Try using .splice() instead of .push()

$scope.addRo=function(index){
  var inderted={
    id: '',
    name: ''
  };
  $scope.rows.splice(index + 1, 0, inderted);
}

Here's the docs for .splice()

Also, there is no need to add 'inderted' to scope if you are just using it temporarily.

Upvotes: 1

dfsq
dfsq

Reputation: 193271

To insert new element in the array you need to use Array.prototype.splice method. In your case:

$scope.rows.splice($index+1, 0, $scope.inserted);

Upvotes: 0

Related Questions