ng-repeat中的独特计数器

时间:2016-09-21 18:56:52

标签: javascript angularjs angularjs-ng-repeat

我有15行这张桌子。

Plunkr

代码:

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body ng-app="myApp">

<table ng-controller="myCtrl" border="1">
<tr ng-repeat="item in myObj">
  <td>{{$index +1}}</td>
  <td>{{item.Name}}</td>
</tr>
</table>

<script>
var app = angular.module("myApp", []);
app.controller("myCtrl", function($scope) {
  $scope.myObj = [    {
      "Name": "Alfreds Futterkiste",
      "City": "Berlin",
      "Country": "Germany"
    },
    {
      "Name": "Ana Trujillo Emparedados y helados",
      "City": "México D.F.",
      "Country": "Mexico"
    },
    {
      "Name": "Antonio Moreno Taquería",
      "City": "México D.F.",
      "Country": "Mexico"
    },
    {
      "Name": "Around the Horn",
      "City": "London",
      "Country": "UK"
    },
    {
      "Name": "B's Beverages",
      "City": "London",
      "Country": "UK"
    },
    {
      "Name": "Berglunds snabbköp",
      "City": "Luleå",
      "Country": "Sweden"
    },
    {
      "Name": "Blauer See Delikatessen",
      "City": "Mannheim",
      "Country": "Germany"
    },
    {
      "Name": "Blondel père et fils",
      "City": "Strasbourg",
      "Country": "France"
    },
    {
      "Name": "Bólido Comidas preparadas",
      "City": "Madrid",
      "Country": "Spain"
    },
    {
      "Name": "Bon app'",
      "City": "Marseille",
      "Country": "France"
    },
    {
      "Name": "Bottom-Dollar Marketse",
      "City": "Tsawassen",
      "Country": "Canada"
    },
    {
      "Name": "Cactus Comidas para llevar",
      "City": "Buenos Aires",
      "Country": "Argentina"
    },
    {
      "Name": "Centro comercial Moctezuma",
      "City": "México D.F.",
      "Country": "Mexico"
    },
    {
      "Name": "Chop-suey Chinese",
      "City": "Bern",
      "Country": "Switzerland"
    },
    {
      "Name": "Comércio Mineiro",
      "City": "São Paulo",
      "Country": "Brazil"
    }]
});
</script>

</body>
</html>

以及输出:

enter image description here

假设我删除了数组中的一个对象,总行将为14,当我将一个对象添加到数组中时,它将返回15。这是预期的。

现在我要做的是,WITHOUT使用控制器,一切都在VIEW完成;删除对象并将其添加回来后,我希望该行显示为16而不是15。我的意思是$index应该增加而不是减少。

我已经使用控制器完成了它,但是它是否可以仅在视图中进行?

感谢您的时间和任何提前的帮助。

1 个答案:

答案 0 :(得分:1)

您可以“软删除”该行。您可以将其标记为已删除,而不是将其从阵列中实际删除。然后,当您添加项目时,计数将继续增加:

function softDelete(item) {
  item.deleted = true;
}

我不知道为什么你不想使用控制器,但这也可以在视图中完成:

<tr ng-repeat="item in myObj" ng-click="item.deleted = true" ng-hide="item.deleted">
  <td>{{$index +1}}</td>
  <td>{{item.Name}}</td>
</tr>

以下是一名示威者:

https://plnkr.co/edit/yuAIXn5Pe9YbwxXW2qih?p=preview