如何使用ng-click从数组中删除项目或对象?

问题描述 投票:248回答:10

我正在尝试编写一个函数,使我能够在单击按钮时删除项目,但我认为我对该函数感到困惑 - 我是否使用$digest

HTML和app.js:

<ul ng-repeat="bday in bdays">
  <li>
    <span ng-hide="editing" ng-click="editing = true">{{bday.name}} | {{bday.date}}</span>
    <form ng-show="editing" ng-submit="editing = false">
      <label>Name:</label>
      <input type="text" ng-model="bday.name" placeholder="Name" ng-required/>
      <label>Date:</label>
      <input type="date" ng-model="bday.date" placeholder="Date" ng-required/>
      <br/>
      <button class="btn" type="submit">Save</button>
      <a class="btn" ng-click="remove()">Delete</a>
    </form>
  </li>
</ul>

$scope.remove = function(){
  $scope.newBirthday = $scope.$digest();
};
html angularjs edit
10个回答
533
投票

要删除项目,您需要将其从数组中删除,并可以将bday项目传递给标记中的删除功能。然后在控制器中查找item的索引并从数组中删除

<a class="btn" ng-click="remove(item)">Delete</a>

然后在控制器中:

$scope.remove = function(item) { 
  var index = $scope.bdays.indexOf(item);
  $scope.bdays.splice(index, 1);     
}

Angular将自动检测bdays数组的更改并执行ng-repeat的更新

但是:ぁzxswい

编辑:如果使用服务器进行实时更新将使用您使用http://plnkr.co/edit/ZdShIA?p=preview创建的服务来同时管理阵列更新它更新服务器


0
投票

如果您的项目中有ID或任何特定字段,则可以使用filter()。它的行为就像Where()。

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice

在控制器中:

<a class="btn" ng-click="remove(item)">Delete</a>

0
投票
$scope.remove = function(item) { 
  $scope.bdays = $scope.bdays.filter(function (element) {
                    return element.ID!=item.ID
                });
}

来自控制器(功能可以在同一个控制器中,但更喜欢将其保留在服务中)

Pass the id that you want to remove from the array to the given function 

51
投票

这是一个正确的答案:

$resource

在@ charlietfl的回答中。我认为这是错误的,因为你将<a class="btn" ng-click="remove($index)">Delete</a> $scope.remove=function($index){ $scope.bdays.splice($index,1); } 作为参数传递,但你在控制器中使用了愿望。如我错了请纠正我 :)


24
投票

in case you're inside an ng-repeat

你可以使用一个班轮选项

$index

<div ng-repeat="key in keywords"> <button ng-click="keywords.splice($index, 1)"> {{key.name}} </button> </div> 由angular用于显示$index内的数组的当前索引


22
投票

使用ng-repeat在基本情况下运行得非常好,@ charlietfl的答案很棒。但有时候,$index还不够。

想象一下,你有一个单独的数组,你在两个不同的ng-repeat中呈现。其中一个ng-repeat是针对具有truthy属性的对象进行过滤,另一个针对falsy属性进行过滤。呈现两个不同的滤波阵列,其源自单个原始阵列。 (或者,如果它有助于可视化:也许你有一个单独的人群,你想要为该阵列中的女性进行一次ng-repeat,另一次为同一阵列中的男性。)你的目标:从中可靠地删除原始数组,使用来自已过滤数组成员的信息。

在每个过滤的数组中,$ index将不是原始数组中项目的索引。它将是过滤子阵列中的索引。因此,您将无法在原始$index数组中告诉该人的索引,您只能知道peoplewomen子数组中的$ index。尝试使用它删除,除了你想要的地方,你将有物品从任何地方消失。该怎么办?

如果你很幸运,使用数据模型包含每个对象的唯一标识符,然后使用它而不是$ index,从主数组中找到对象和men。 (使用下面的示例,但使用该唯一标识符。)但是,如果你没那么幸运?

Angular实际上使用一个名为splice的唯一属性来扩充ng重复数组(在主要的原始数组中)中的每个项目。您可以在原始数组中搜索要删除的项目的$$hashKey上的匹配项,并以此方式删除它。

请注意,$$hashKey是一个实现细节,未包含在已发布的ng-repeat API中。他们可以随时取消对该物业的支持。但可能不是。 :-)

$$hashKey

调用:

$scope.deleteFilteredItem = function(hashKey, sourceArray){
  angular.forEach(sourceArray, function(obj, index){
    // sourceArray is a reference to the original array passed to ng-repeat, 
    // rather than the filtered version. 
    // 1. compare the target object's hashKey to the current member of the iterable:
    if (obj.$$hashKey === hashKey) {
      // remove the matching item from the array
      sourceArray.splice(index, 1);
      // and exit the loop right away
      return;
    };
  });
}

编辑:使用这样的函数,ng-click="deleteFilteredItem(item.$$hashKey, refToSourceArray)" 上的哪些键而不是模型特定的属性名称,也具有使这个函数可以在不同的模型和上下文中重用的显着附加优势。提供您的数组引用和项目引用,它应该可以正常工作。


9
投票

我经常写这样的风格:

$$hashKey

希望这会有所帮助你必须在$ scope和[yourArray]之间使用一个点(。)


8
投票

在接受的答案的基础上,这将与<a class="btn" ng-click="remove($index)">Delete</a> $scope.remove = function(index){ $scope.[yourArray].splice(index, 1) }; ngRepeatand处理更好的处理:

控制器:

filter

视图:

vm.remove = function(item, array) {
  var index = array.indexOf(item);
  if(index>=0)
    array.splice(index, 1);
}

4
投票

没有控制器的实现。

ng-click="vm.remove(item,$scope.bdays)"

splice()方法向/从数组添加/删除项。

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<body>

<script>
  var app = angular.module("myShoppingList", []); 
</script>

<div ng-app="myShoppingList"  ng-init="products = ['Milk','Bread','Cheese']">
  <ul>
    <li ng-repeat="x in products track by $index">{{x}}
      <span ng-click="products.splice($index,1)">×</span>
    </li>
  </ul>
  <input ng-model="addItem">
  <button ng-click="products.push(addItem)">Add</button>
</div>

<p>Click the little x to remove an item from the shopping list.</p>

</body>
</html>

index:必需。一个整数,指定添加/删除项目的位置,使用负值指定数组末尾的位置。

howmanyitem(s):可选。要删除的项目数。如果设置为0,则不会删除任何项目。

item_1,...,item_n:可选。要添加到数组的新项目


3
投票

我不同意你应该在你的控制器上调用一个方法。您应该使用服务来实现任何实际功能,并且您应该为可伸缩性和模块化的任何功能定义指令,以及分配包含对您注入到指令中的服务的调用的单击事件。

那么,例如,在您的HTML上......

array.splice(index, howmanyitem(s), item_1, ....., item_n)

然后,创建一个指令......

<a class="btn" ng-remove-birthday="$index">Delete</a>

然后在你的服务中......

angular.module('myApp').directive('ngRemoveBirthday', ['myService', function(myService){
    return function(scope, element, attrs){
        angular.element(element.bind('click', function(){
            myService.removeBirthday(scope.$eval(attrs.ngRemoveBirthday), scope);  
        };       
    };
}])

当您像这样正确地编写代码时,无需重构代码就可以很容易地编写未来的更改。它组织正确,您通过使用自定义指令绑定正确处理自定义单击事件。

例如,如果你的客户说,“嘿,现在让它让它调用服务器并制作面包,然后弹出一个模态。”您将能够轻松地转到服务本身,而无需添加或更改任何HTML和/或控制器方法代码。如果你只有控制器上的一行,你最终需要使用一项服务,将功能扩展到客户要求的更重的提升。

此外,如果您在其他地方需要另一个“删除”按钮,您现在可以轻松地分配到页面上的任何元素的指令属性('ng-remove-birthday')。这使它成为模块化和可重复使用的。在处理Angular 2.0的HEAVY Web组件范例时,这将派上用场。 2.0中没有控制器。 :)

快乐发展!!!


1
投票

这是另一个答案。我希望它会有所帮助。

angular.module('myApp').factory('myService', [function(){
    return {
        removeBirthday: function(birthdayIndex, scope){
            scope.bdays.splice(birthdayIndex);
            scope.$apply();
        }
    };
}]);

完整的来源在这里 <a class="btn" ng-click="delete(item)">Delete</a> $scope.delete(item){ var index = this.list.indexOf(item); this.list.splice(index, 1); } array.splice(start) array.splice(start, deleteCount) array.splice(start, deleteCount, item1, item2, ...)

© www.soinside.com 2019 - 2024. All rights reserved.