角度 - 拼接从数组中删除除所需对象以外的任何内容

Angular - splice removes anything but the needed object from the array

本文关键字:对象 任何内 拼接 数组 删除 角度      更新时间:2023-09-26

我正在尝试从简单的电话簿应用程序中删除联系人。但是,当我调用 deletePerson 函数时,除了所需的联系人之外,我会删除任何内容。请告诉我我的错误伙计们。

我的联系人部分:

<ul class="people-list">
    <li showhideoptions ng-repeat="person in people | filter: search | 
                                   orderBy: 'name' | orderBy:'friend':true">
        <h4>
            <span ng-show="person.friend==true" class="icon-star icon-left"></span>
            <span ng-show="person.friend==false" class="icon-user icon-left"></span>
        {{person.name}}
        <span ng-click="deletePerson($index)"
          class="icon-remove pull-right"></span>
          </h4>
    </li>
</ul>

我的出厂主控制器:

var app = angular.module('contactList');
app.factory('simpleFactory', function(){
    var people = [
            {name: 'Collin', city: 'Omaha', friend: false},
            {name: 'Alice', city: 'New York', friend: false},
            {name: 'Pasha', city: 'Moscow', friend: true},
            {name: 'Denis', city: 'St. Pete', friend: true}
    ];
    var factory = {};
    factory.getPeople = function() {
        return people;
    };
    return factory;
});
app.controller('MainController', function ($scope, simpleFactory) {
$scope.people = [];
init();
function init() {
    $scope.people = simpleFactory.getPeople();
}
$scope.addPerson = function() {
    $scope.people.push(
    {   name: $scope.newPerson.name, 
        city: $scope.newPerson.city,
        friend: false
    });
};
$scope.deletePerson = function($index) {
    $scope.people.splice($index, 1);
}
  });

UPD

我现在明白过滤器

 | filter: search | orderBy: 'name' | orderBy:'friend':true"

让我的删除过程变得疯狂。如果有人能就如何解决这个问题向我提供建议,我将不胜感激!

您可以使用项目本身进行删除,例如

.HTML

 <span ng-click="deletePerson(person)"
          class="icon-remove pull-right">
 </span>

.JS

$scope.deletePerson = function(item) {
    $scope.people.splice($scope.people.indexOf(item), 1);
}