Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove an item from an array in AngularJS scope?

Simple to-do list, but with a delete button on list page for each item:

enter image description here

Relevant template HTML:

<tr ng-repeat="person in persons">
  <td>{{person.name}} - # {{person.id}}</td>
  <td>{{person.description}}</td>
  <td nowrap=nowrap>
    <a href="#!/edit"><i class="icon-edit"></i></a>
    <button ng-click="delete(person)"><i class="icon-minus-sign"></i></button>
  </td>
</tr>

Relevant controller method:

$scope.delete = function (person) {
  API.DeletePerson({ id: person.id }, function (success) {
    // I need some code here to pull the person from my scope.
  });
};

I tried $scope.persons.pull(person) and $scope.persons.remove(person).

Although the database deleted successfully, I can not pull this item from scope and I do not want to make a method call to the server for data the client already has, I just want to remove this one person from scope.

Any ideas?

like image 901
Bye Avatar asked Sep 29 '22 04:09

Bye


People also ask

How can I remove a specific item from an array?

pop() function: This method is use to remove elements from the end of an array. shift() function: This method is use to remove elements from the start of an array. splice() function: This method is use to remove elements from the specific index of an array.

How do I remove an item from an array by value?

To remove an item from a given array by value, you need to get the index of that value by using the indexOf() function and then use the splice() function to remove the value from the array using its index.

How do you clear an array in AngularJS?

The task is to make empty an array or delete all elements from the array in AngularJS. Approach: First example uses the [] notation to reinitialize the array which eventually removes all the elements from the array. Second example sets the length of the array to 0 by using length property, which also empty the array.

How do I remove something from an array in TypeScript?

To remove an object from a TypeScript array:Use the findIndex() method to get the index of the object. Use the splice() method to remove the object from the array. The splice method will remove the object from the array and will return the removed object.


1 Answers

You'll have to find the index of the person in your persons array, then use the array's splice method:

$scope.persons.splice( $scope.persons.indexOf(person), 1 );
like image 311
Joseph Silber Avatar answered Oct 19 '22 09:10

Joseph Silber