如何在不允许 table 为空的情况下删除 ng-repeat table 行?

How to remove ng-repeat table row without allowing the table to be empty?

我正在尝试删除 table 中的行,但我不希望它永远是空的... table 从一行开始,但用户可以添加新行但也删除所有行,使 table 为空。这是我在控制器中添加和删除行的代码:

$scope.rowItems = [{}];

$scope.addRowItems = function() {
    $scope.rowItems.push(rowItem); 
}

$scope.deleteRowItem = function(item) {
    $scope.rowItems.splice(item, 1);
}

这是我的代码 HTML:

<tr ng-repeat:"rowItem in rowItems track by $index">
   ...rest of row here...
</tr>

我们将不胜感激!

您可以在拼接之前检查数组的长度,并且可以选择向用户显示一个警告,警告他至少有一行应该出现在 table。

$scope.deleteRowItem = function(item) {
  if($scope.rowItems.length > 1) {
    $scope.rowItems.splice(item, 1);
  } else {
    alert("Can't remove the only row");
  }
}

您可以像这样在 HTML 视图中添加静态行:

<tr>
   ...static row columns are here...
</tr>
<tr ng-repeat:"rowItem in rowItems track by $index">
   ...rest of row here...
</tr>

这是个好主意,因为您可以在第一个 tr 中添加操作 buttons/input,然后只需添加操作事件即可添加新行或其他内容

或者您可以限制删除组件逻辑中的行,如 @31piy

所示