cfoster5
cfoster5

Reputation: 1826

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?

Upvotes: 1

Views: 1396

Answers (2)

CodeSmith
CodeSmith

Reputation: 3197

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

Upvotes: 3

Mike Tung
Mike Tung

Reputation: 4821

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

Upvotes: 0

Related Questions