user3130985
user3130985

Reputation: 411

Delete object reference in javascript

I am pretty new in js and angularjs and ran into some basic problem i can't solve. I add the $scope.consignations to the view with ng-repeat. Its a big object with several layers. In the sample code, i assign the $scope.consignations to the temp and after that, i "navigate" inside the temp object and at some point i push data to the temp. It changes the view, as expected.Now i want to clear the $scope[elementName] obj, but it clears the pushed data as well from the view. I've tried to delete the temp reference (i assume its only a reference of the $scope.consignations obj.) and i cant access it anymore, but when i clear the $scope[elementName] it clears the view anyway.

$scope.addElements = function(elementName){ 
    temp=$scope.consignations;

    for (var key in someArray) {
      //here i "navigate" recursive inside temp 
    }
    temp.push($scope[elementName]);
    delete temp;
    for (var key in $scope[elementName]) {
         $scope[elementName][key]="";
    }
};

Upvotes: 0

Views: 1075

Answers (3)

Xandrios93
Xandrios93

Reputation: 2305

In case you are using definedProperty, angular will not copy these.
This snippet will help you out then.

Upvotes: 0

Juned Lanja
Juned Lanja

Reputation: 1474

temp=$scope.consignations by doing so your temp & $scope.consignations references same object. So change in any object will be reflected in other object as well as in view.

So you should copy it like $scope.temp=angular.copy($scope.consignations) and then use $scope.temp for view binding and $scope.consignations for other purpose.

Upvotes: 1

Partha Sarathi Ghosh
Partha Sarathi Ghosh

Reputation: 11576

If you want to copy an existing element from $scope to a new $scope variable and delete the old one then you can use the following approch.

$scope.consignations.push(angular.copy($scope[elementName]));
delete $scope[elementName];

Assuming $scope.consignations is you new array where you want to store the data and $scope[elementName] is your old one which you want to delete.

Upvotes: 0

Related Questions