如何在 AngularJS 中从列表中删除项目并更新列表?



>我的项目中有平台列表,我想从平台列表中删除一个项目并查看更新列表而无需重新加载 平台列表图像:平台列表图像

我在项目中使用 UI-路由

平台列表正文.html :

<tbody>
<tr ng-repeat="platform in platforms">
<td>{{platform.PlatformID}}</td>
<td>{{platform.Name}}</td>
<td><button ui-sref="platform-edit({id: platform.PlatformID})" class="btn btn-warning">Edit&nbsp;<span class="glyphicon glyphicon-edit" aria-hidden="true"></span></button>&nbsp;|&nbsp;
<button ng-click="remove(platform.PlatformID)"  class="btn btn-danger">Delete&nbsp;<span class="glyphicon glyphicon-remove" aria-hidden="true"></span></button></td>
</tr>
</tbody>

平台列表控制器.js :

mainApp.controller('platformListController', function ($scope, platform, $filter) {
platform.query().$promise.then(function (data) {
$scope.platforms = data;
}, function (error) {
});    
});

平台型号 :

public class Platform
{        
[Key]
public int PlatformID { get; set; }    
public string Name { get; set; }
}

如何在此控制器中编写删除代码?

这段代码解决了你的问题:

mainApp.controller('platformListController', function ($scope, platform, $filter) {    
platform.query().$promise.then(function (data) {
$scope.platforms = data;
}, function (error) {
});
//add this code 
$scope.remove = function (id) {
platform.remove({ id: id }).$promise.then(function () {
$scope.platforms = $filter('filter')($scope.platforms, function (item) {
return item.PlatformID !== id;
});
alert('Removed');
}, function (error) {
alert('Failed');
});
};
//
});

您可以使用array.splice()方法从数组中删除数据。此语法是

array.splice(index , howMany[, element1[, ...[, elementN]]])

在控制器中

mainApp.controller('platformListController', function ($scope, platform, $filter) {
$scope.platforms = [];
platform.query().$promise.then(function (data) {
$scope.platforms = data;
}, function (error) {
});
$scope.remove = function(platformId, index){
$scope.platforms.splice(index,1);
}
});

你的 HTML 应该如下所示:

<tbody>
<tr ng-repeat="platform in platforms">
<td>{{platform.PlatformID}}</td>
<td>{{platform.Name}}</td>
<td><button ui-sref="platform-edit({id: platform.PlatformID})" class="btn btn-warning">Edit&nbsp;<span class="glyphicon glyphicon-edit" aria-hidden="true"></span></button>&nbsp;|&nbsp;
<button ng-click="remove(platform.PlatformID, $index)"  class="btn btn-danger">Delete&nbsp;<span class="glyphicon glyphicon-remove" aria-hidden="true"></span></button></td>
</tr>
</tbody>

$scope.platforms的属性是什么?可能最简单(不是最有效的(是添加ng-click属性。

就代码而言,这将是"删除"按钮的 HTML:

`<btn ng-model="delBtn" ng-click="deletePlatform(platform.id)">
<span>Delete</span>
</btn>`

控制器或指令中的函数将是:

`function deletePlatform(platform.id) {
$scope.platforms.filter(function (platformItem) {
return platformItem.id !== platform.id;
});
}`

最新更新