0

I have a AngularJS method to splice elements from middle of an array but I want to add the elements to be deleted to another array before using splice method. Here is my code

$scope.method = function (index) {
            $scope.array2.push($scope.array1[index]);
            $scope.array1.splice(index, 1);
        }

when I am calling the method array1[index] values could be retreived but they not getting pushed into array2

here is my html code

<div data-ng-repeat="item in array1">
    <button class="btn btn-success pull-right" data-ng-click="method($index)">
        <i class="fa fa-trash" aria-hidden="true"></i>
    </button>
    <br />
</div>
3
  • 1
    Looks like you're splicing inside a loop, altering the array as you go. Commented Oct 12, 2016 at 14:38
  • Is the array2 initialised? Commented Oct 12, 2016 at 14:39
  • js array splice returns array or removed elements. If array1 is an [] the just array1.splice(...).forEach(e=>array2.push(e)); Commented Oct 12, 2016 at 14:40

2 Answers 2

1

Look the function splice It will return your deleted value;

$scope.method = function (index) {
     if(! $scope.array2 ) $scope.array2 = [];
     $scope.array2 = $scope.array2.concat($scope.array1.splice(index, 1););
}
Sign up to request clarification or add additional context in comments.

Comments

1

I change only this part of your code.

$scope.method = function (index) {
        $scope.array2.push($scope.array1.slice(index, 1));
        $scope.array1.splice(index, 1);
};

Check this jsfiddle example

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.