使用AngularJS从数组中删除元素可以通过以下步骤实现:
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.7.9/angular.min.js"></script>
var app = angular.module('myApp', []);
<div ng-app="myApp" ng-controller="myCtrl">
app.controller('myCtrl', function($scope) {
$scope.myArray = [1, 2, 3, 4, 5];
});
<div ng-repeat="item in myArray">
{{ item }}
</div>
$scope.removeItem = function(item) {
var index = $scope.myArray.indexOf(item);
if (index > -1) {
$scope.myArray.splice(index, 1);
}
};
<button ng-click="removeItem(item)">删除</button>
完整的示例代码如下:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.7.9/angular.min.js"></script>
</head>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<div ng-repeat="item in myArray">
{{ item }}
<button ng-click="removeItem(item)">删除</button>
</div>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.myArray = [1, 2, 3, 4, 5];
$scope.removeItem = function(item) {
var index = $scope.myArray.indexOf(item);
if (index > -1) {
$scope.myArray.splice(index, 1);
}
};
});
</script>
</body>
</html>
这样,当点击"删除"按钮时,对应的元素将从数组中删除。
领取专属 10元无门槛券
手把手带您无忧上云