我正在使用 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/