1

I am trying to remove user from the list. For some reason, splicing is not removing the user from the list. Can any one help me solve this. I am getting the users from a backend API call, and I am using a PUT method to update it when it removes that particular user.

app.js

app.controller('MyCtrl', function($scope, $window) {

    $scope.inactive = true;

    $scope.confirmedAction = user => {
        const index = $scope.userInfo.users.indexOf(user);
        $scope.userInfo.users.splice(user, 1);
        $window.location.href = '#/user';
    };

});
Vladimir Zdenek
  • 2,270
  • 1
  • 18
  • 23

2 Answers2

1

you should splice based on index

$scope.userInfo.users.splice(index, 1);

as per the docs Array.prototype.splice

index at which to start changing the array (with origin 0). If greater than the length of the array, actual starting index will be set to the length of the array

just to show a POC

var array = ['val1','val2','val3']
var index = array.indexOf('val2')
array.splice(index,1);

console.log(array);
//['val1','val3']
davidJohn
  • 11
  • 3
0

From comments I noticed:

user is an object, and the function's parameter user is not the same instance!

Also assuming you have id property in user object.

Using Array.findIndex.

app.controller('MyCtrl', function($scope, $window) {
        $scope.inactive = true;
        $scope.confirmedAction = function (user) {
           var index = $scope.userInfo.users.findIndex(u=> u.id == user.id);
          if(index>=0) {
              $scope.userInfo.users.splice(user, 1);
              $window.location.href = '#/user';
          }
        }
    });
A.Akram
  • 412
  • 5
  • 22
  • This didn't work either. Should I post my PUT method code to see it? –  Jun 08 '17 at 02:45
  • where did you declared u.id? –  Jun 08 '17 at 02:58
  • equate both object using angular.equals var index = $scope.userInfo.users.findIndex(u=> angular.equals(u,user)); – Rajniprabha Jun 08 '17 at 04:05
  • @alle I get an error (red scribbly line under => and after the second parenthesis) saying "expecting new line or semicolon" ?? –  Jun 08 '17 at 11:35
  • if you are using e5 var index = $scope.userInfo.users.findIndex(function (u){ return angular.equals(u,user)}); – Rajniprabha Jun 09 '17 at 04:13