Angularjs在当前行位置添加行

Angularjs adding row at curent row location

本文关键字:位置 添加行 Angularjs      更新时间:2023-09-26

我有以下代码,假设在当前行位置(而不是在行的底部)添加另一行:

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

在我的控制器中,我有:

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

我尝试了上面的代码,希望将索引添加到当前位置,它会添加它,但它不起作用。如何解决此问题?

尝试使用.splice()而不是.push()

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

这是.splice() 的文档

此外,如果您只是临时使用"indested",则无需将其添加到作用域中。

要在数组中插入新元素,需要使用Array.prototype.splice方法。在您的情况下:

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

由于您可以访问ng repeat中当前元素的$index,因此插入新行很容易。当前代码的问题是array.push总是将元素添加到数组的

使用array.splice将元素实际插入到数组中。

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