简体   繁体   English

使用.splice从数组中删除项目是删除多个对象

[英]Using .splice to remove an item from an array is removing multiple objects

I have created a page where users can select/ unselect employees. 我创建了一个用户可以选择/取消选择员工的页面。 I am using .push to add these employees to an array, users . 我正在使用.push将这些员工添加到数组users I am also using .splice to remove the unchecked item from the array. 我也使用.splice从数组中删除未经检查的项目。 Currently, unchecking the last checked item works fine, however, if I select multiple items and uncheck the first item displayed in the view, it will remove every item from the array. 目前,取消选中上次检查的项目可以正常工作,但是,如果我选择多个项目并取消选中视图中显示的第一个项目,它将从阵列中删除每个项目。

Here is the HTML: 这是HTML:

<div ng-app="myApp">
  <div ng-controller="MainCtrl">
    <table>
      <tr ng-repeat="user in users">
        <td><input type="checkbox" ng-model="checked" ng-change="addremoveuser(checked, user.ID)"><td>
        <td>{{user.Title}}</td>
        <td>{{user.FirstName}}</td>
        <td>{{user.LastName}}</td>
      </tr>
    </table>
  </div>
</div>

Here is the JS: 这是JS:

var app = angular.module('myApp', ['ngSanitize']);
app.controller('MainCtrl', function($scope, $http, $q){
    var users = [];
    $scope.addremoveuser = function (checked, id) {
        if (checked) {
            console.log("user selected", id);
            users.push(id)
            console.log("if test", users);
        }
        else {
            console.log("user unselected", id);
            var index = users.indexOf(id);
            users.splice(index);
            console.log("else test", users);
        }
    };
});

How can I fix this to only remove the item that was unchecked? 如何解决此问题仅删除未选中的项目?

users.splice(index);

should be: 应该:

users.splice(index, 1);

Look at documentation: 看看文档:

Array.splice() 方法Array.splice()

Also, take care what id is. 另外,要注意id是什么。 Is it an ill named element or actual id of element in array? 它是一个病态的命名元素还是数组中元素的实际id Cause if its id of element in array you don't need that indexOf(id) . 如果它在数组中的元素的id你不需要indexOf(id)

It's a bit dangerous to splice and mutate your array. 拼接和改变数组有点危险。 One strategy to help with adding/removing users is to simply use filter . 帮助添加/删除用户的一种策略是简单地使用filter

var users = [];
$scope.addremoveuser = function (checked, id) {
    if (checked) {
        console.log("user selected", id);
        users.push(id)
        console.log("if test", users);
    }
    else {
        console.log("user unselected", id);
        users = users.filter(function(user) {
          return user.id === id;
        }
        console.log("else test", users);
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM