Jośe
Jośe

Reputation: 125

How to make delete button delete a user in AngularJS?

I am new to AngularJS, and I need some help of trying to make the delete button, to delete a user in AngularJS. If anyone can help, I will be thankful. Thanks in advance.

Here is my delete button I have created

<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];


   });
  }]);

Upvotes: 0

Views: 7789

Answers (2)

Surjeet Bhadauriya
Surjeet Bhadauriya

Reputation: 7156

So in ng-click call a function named deleteUser and pass the id you are getting for that user.

//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> 

So now inside you controller make a function to delete the user. If you are using it inside the ng-repeat then you should pass parameters accordingly. According to your code, you may pass it.

 //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);
 }

Here is a plunker example. https://plnkr.co/edit/GbKHSER1r992D5ImXJ7n?p=preview

Upvotes: 2

mazipan
mazipan

Reputation: 183

You must fill ng-click action to your function in your controller. If your button was in ng-repeat maybe you must sent parameter in you delete function.

Upvotes: 0

Related Questions