1

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?

0

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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);

Comments

0

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
    };

Comments

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.