I have two arrays
which contain certain values the first array
is predefined and the second array
is equal to the first array
. The second array
itself is an array
auxiliary which I use to remove elements. The error I have is that when I remove elements from the second array
the elements from the first are also deleted array
, This is my code:
At the time of verifying my array
it is empty. How can I resolve this error? and here my jsfiddle
function Ctrl($scope) {
$scope.categorias = [{"id_categoria":2,"id_empresa":2},{"id_categoria":3,"id_empresa":2}];
$scope.categorias_Aux = $scope.categorias;
$scope.eliminar_categoria = function(id_categoria){
for (var i = 0; i < $scope.categorias_Aux.length; i++){
if ($scope.categorias_Aux[i].id_categoria == id_categoria) {
$scope.categorias_Aux.splice(i, 1);
break;
}
}
console.log(JSON.stringify($scope.categorias))
}
$scope.verificar = function(){
$scope.categorias_Aux = $scope.categorias;
console.log(JSON.stringify($scope.categorias_Aux))
}
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app>
<div ng-controller="Ctrl">
<table style="width:100%">
<tr>
<th>Nom</th>
<th>id</th>
<th>accion</th>
</tr>
<tr ng-repeat="i in categorias_Aux">
<td>nombre cat</td>
<td>{{i.id_categoria}}</td>
<td><input type="button" value="x" ng-click="eliminar_categoria(i.id_categoria)"></td>
</tr>
</table>
<input type="button" ng-click="verificar()">
</div>
</div>
The problem you have is that when you do,
$scope.categorias_Aux = $scope.categorias;
you are also copying the reference in memory of$scope.categorias
a$scope.categorias_Aux
in such a way that what you do to one will affect both.To clone the array, you would initialize the array
$scope.categorias_Aux = []
and then iterate over the original array and insert the data.Or in a more optimal way,
$scope.categorias_Aux = $scope.categorias.slice(0);
it will also copy the data, without copying the reference.Difference between Shallow copy and Deep copy
I have changed the code somewhat to make it more visual. I've been giving it a thousand times, and the only thing I've found is that instead of matching them with
=
you have to use.copy()
. Since with the first it is as if you were related and with the second they are two separate elements. FontPS: for more information about copy, I have posted a question