1

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?

1
  • pass $index instead addremoveuser(checked, $index) -> users.splice(id); Commented Jan 18, 2018 at 14:40

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.