如何使删除按钮删除AngularJS中的用户



我是AngularJS的新手,我需要尝试进行删除按钮,以删除AngularJS中的用户。如果有人可以提供帮助,我会很感激。提前致谢。

这是我创建的删除按钮

<button type="button" 
         class="delete" 
          ng-click="" 
          ng-show="!inactive">Delete</button> 
    //The user view 
   <div class="people-view">
  <h2 class="name">{{people.first}}</h2>
    <h2 class="name">{{people.last}}</h2>
  <span class="title">{{people.title}}</span>
  <span class="date">{{people.date}} </span>

</div> 

//Controller
 app.controller('MainController',['$scope', 'people', '$routeParams',
function($scope, people, $routeParams) {
people.success(function(data) {
 $scope.people = data[$routeParams.id];

   });
  }]);

因此,在ng-click中调用名为deleteUser的函数,并传递您为该用户获得的ID。

//HTML
<button type="button" 
         class="delete" 
          ng-click="deletePeople(id)" 
          ng-show="!inactive">Delete</button> 
//The user view 
<div class="people-view">
  <h2 class="name">{{people.first}}</h2>
  <h2 class="name">{{people.last}}</h2>
  <span class="title">{{people.title}}</span>
  <span class="date">{{people.date}} </span> 
</div> 

因此,现在您的控制器内部可以删除用户。如果您在ng-repeat内使用它,则应相应地传递参数。根据您的代码,您可以通过它。

 //Controller
 $scope.deletePeople = function (id){
  //here comes your delete code.
  //pass id from the ng-click function.
  //based on that id find the record in the $scope.people array and remove that from the array.
  //you can use javascript splice function to remove it.
  var userToDelete;
  $scope.people.forEach(function(p, index){
    if(p.id == id){
       userToDelete = index;
    }
  });
  $scope.people.splice(userToDelete, 1);
 }

这是一个备用示例。https://plnkr.co/edit/gbkhser1r992d5imxj7n?p=preview

您必须在控制器中填充ng-click操作。如果您的按钮在ng-repeat中,也许您必须在删除函数中发送参数。

最新更新