javascript - 按按钮从数组中删除项目

标签 javascript arrays angularjs

我正在使用 angularJS 构建 SPA。我正在尝试从 Controller 中的数组中删除一个对象。我正在使用 ng-repeat,但似乎无法理解这个问题。相关html如下:

<div class="cat-button" ng-repeat="category in cats" category="category">
         <button class=" close-button" ng-click="removeCat()">
         <span class="glyphicon glyphicon-remove-sign" aria-hidden=true> </span> </button>{{category.name}}
</div>

这为保存到我的 $scope.cats 数组中的每个对象创建了一个带有按钮的 div。它工作正常,但我不知道如何使用每个 div 中的按钮来删除该特定对象。

当我单击按钮时, Controller 上的函数被调用,但这就是我迷失的地方,如何删除用户动态创建的特定对象。

这是我的 Controller 上的相关代码:

 //Function to delete category

$scope.removeCat = function () {

   //I know I have to use splice on my array but how do I Identify the object that needs to be deleted from my array?



};

最佳答案

您可以传递$index像这样:

<button class=" close-button" ng-click="removeCat($index)">

在你的函数中:

$scope.removeCat = function (index) {
    $scope.cats.splice(index,1);
}

或者传递整个项目并使用indexOf(更节省的方式)

<button class=" close-button" ng-click="removeCat(category)">

$scope.removeCat = function (item) {
    $scope.cats.splice(myArray.indexOf(item), 1);
}

关于javascript - 按按钮从数组中删除项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34987109/

相关文章:

javascript - 如何让我的 Phaser 游戏射出不止一支箭?

javascript - 如何在 axios 请求中返回计算属性内的数据

javascript - RxJs:通过distinctUntilChanged() 过滤顺序获取哪些对象键已更改,而不保留外部状态

javascript - 如何仅以特定格式在数组中添加动态键?

javascript - 使用 jasmine 测试路由时 Angular 为空 $state 名称

javascript - 如何使保存的对象立即出现在 ng-repeat 中?

javascript - 如何让字体图标充满 block 元素?

php - 在 PHP (PDO) 中了解 MySQL 的内存使用情况

C++ 去掉前导零

javascript - 在 JavaScript 中将数组作为内置函数参数传递