ajmajmajma
ajmajmajma

Reputation: 14216

angular, remove anything from scope with same key value

I have an array stored in a scope, when I click a button on then in the repeat, I want anything that has the same key value of skillId to be removed from the array. Here's my attempt

$scope.deleteSkill = function(skill) {  

     for (var i=0; i<$scope.pathArray.length; i++){

        if($scope.pathArray[i].skillId == skill){
            $scope.pathArray.splice(i,1);
        }
    };

};

The delete is in the repeat on the item, and the "skill" being passed is it's skillId (this is wokring fine). I am trying to loop through the scopes array and remove anything with the same skillId. I tried looping like so and checking if skillId = skill. My current logic does not seem to work, it only removes 1 item if there are multiples. Any help would be great. Thanks!

Upvotes: 0

Views: 124

Answers (2)

zs2020
zs2020

Reputation: 54524

The trick is loop the array from the end to the beginning, since the length of the array changes due to removing elements.

$scope.deleteSkill = function (skill) {
    for (var i = $scope.pathArray.length - 1; i >= 0; i--) {
        if ($scope.pathArray[i].skillId == skill) {
            $scope.splice(i, 1);
        }
    };
};

Upvotes: 2

Ronnie
Ronnie

Reputation: 11198

to go with my comment above, do something as simple as comparing the opposite

$scope.deleteSkill = function(skill)
{
    var temp = [];
    for (var i = 0; i < $scope.pathArray.length; i++)
    {
      if ($scope.pathArray[i].skillId != skill) temp.push(skill) //push skill or whatever the array value is
    }
    $scope.pathArray = temp;
};

Upvotes: 1

Related Questions