SrinivasAppQube
SrinivasAppQube

Reputation: 301

Deleting the array with splice not working properly?

When i click on button value will be push to another array. next i click on the same button the pushing item will be deleted. in my project pushing done properly.but second time click on the same button first element in the array deleted not the selected one.

this is my html code.

<a  class="btn {{table.btnClass}} btn-success"  ng-click="getTable(table)" style="padding-left:1px">{{table.tablename}}</a>

This is my controller code

$scope.tableArray=[]
$scope.tableslist=[]
$scope.getTable=function(table){
    table.btnClass = table.btnClass == "btn-danger" ? "btn-success" : "btn-danger"
    console.log(table)
    var exists=false;
    angular.forEach($scope.tableArray, function (list) {
        if ((list.tablename == table.tablename)) {
            console.log(list.tablename)
             console.log(table.tablename)
            exists=true;
            $scope.tableArray.splice(list._id,1)
            return false
        }
     });
  if(!exists){
  $scope.tableslist.push(table)
  $scope.tableArray=$scope.tableslist
  console.log($scope.tableArray)
   table.color="red"
    }
}

please help me

Upvotes: 2

Views: 2806

Answers (3)

Ricky Boy
Ricky Boy

Reputation: 783

Came across the similar problem with Splice. In my case, I had to resolve as below just incase if it helps someone.

If you are dealing with objects, please note indexOf works for array not for an Object inside that array. You can do something like below to identify the index and handle this case;

$scope.removeReport = function(report) {
    var index = $scope.contact.reports.map(function(r) { return r.id;}).indexOf(report.id);
        if (index >= 0) {
          $scope.contact.reports.splice(index, 1);
        }
}

Upvotes: 0

tamil
tamil

Reputation: 118

For delete the selected item in an array you can use the indexOf as I mentioned below.

  $scope.tableArray.splice($scope.tableArray.indexOf(list),1);         

Upvotes: 0

byteC0de
byteC0de

Reputation: 5273

add a second argument in foreach, use index to splice from array

 angular.forEach($scope.tableArray, function (list, index) {
    ----------
    -------------------
    $scope.tableArray.splice(index,1)
 })

Upvotes: 3

Related Questions