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

后端 未结 10 1735
梦毁少年i
梦毁少年i 2020-11-27 09:10

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

Relevant template HTML:


          


        
10条回答
  •  孤城傲影
    2020-11-27 09:34

    Your issue is not really with Angular, but with Array methods. The proper way to remove a particularly item from an array is with Array.splice. Also, when using ng-repeat, you have access to the special $index property, which is the current index of the array you passed in.

    The solution is actually pretty straightforward:

    View:

    Delete
    

    Controller:

    $scope.delete = function ( idx ) {
      var person_to_delete = $scope.persons[idx];
    
      API.DeletePerson({ id: person_to_delete.id }, function (success) {
        $scope.persons.splice(idx, 1);
      });
    };
    

提交回复
热议问题