简体   繁体   中英

How to push values from an array to another array before using `splice` method in AngularJS?

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>

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM