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

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

提交回复
热议问题