简体   繁体   中英

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 . I am also using .splice to remove the unchecked item from the array. 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:

<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:

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()

Also, take care what id is. Is it an ill named element or actual id of element in array? Cause if its id of element in array you don't need that 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 .

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);
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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