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

后端 未结 10 1692
梦毁少年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:

    <a ng-click="delete($index)">Delete</a>
    

    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);
      });
    };
    
    0 讨论(0)
  • 2020-11-27 09:35

    You can also use this

    $scope.persons = $filter('filter')($scope.persons , { id: ('!' + person.id) });
    
    0 讨论(0)
  • 2020-11-27 09:40

    I would use the Underscore.js library that has a list of useful functions.

    without

    without_.without(array, *values)
    

    Returns a copy of the array with all instances of the values removed.

    _.without([1, 2, 1, 0, 3, 1, 4], 0, 1);
    // => [2, 3, 4]
    

    Example

    var res = "deleteMe";
    
    $scope.nodes = [
      {
        name: "Node-1-1"
      },
      {
        name: "Node-1-2"
      },
      {
        name: "deleteMe"
      }
    ];
        
    $scope.newNodes = _.without($scope.nodes, _.findWhere($scope.nodes, {
      name: res
    }));
    

    See Demo in JSFiddle.


    filter

    var evens = _.filter([1, 2, 3, 4, 5, 6], function(num){ return num % 2 == 0; });
    
    // => [2, 4, 6]
    

    Example

    $scope.newNodes = _.filter($scope.nodes, function(node) {
      return !(node.name == res);
    });
    

    See Demo in Fiddle.

    0 讨论(0)
  • 2020-11-27 09:40

    If you have any function associated to list ,when you make the splice function, the association is deleted too. My solution:

    $scope.remove = function() {
        var oldList = $scope.items;
        $scope.items = [];
    
        angular.forEach(oldList, function(x) {
            if (! x.done) $scope.items.push( { [ DATA OF EACH ITEM USING oldList(x) ] });
        });
    };
    

    The list param is named items. The param x.done indicate if the item will be deleted.

    Another references: Another example

    Hope help you. Greetings.

    0 讨论(0)
  • 2020-11-27 09:43

    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 );
    
    0 讨论(0)
  • 2020-11-27 09:47
    $scope.removeItem = function() {
        $scope.items.splice($scope.toRemove, 1);
        $scope.toRemove = null;
    };
    

    this works for me!

    0 讨论(0)
提交回复
热议问题