1

It seems that angular.copy() is not properly working on one of the items that I am using it on. Here's the sample code and the screenshot that follows.

    console.log("Copy");
    $scope.traffic_data = traffic_data;
    $scope.total_data = total_data;
    console.log($scope.traffic_data);
    console.log($scope.total_data);

    console.log("Original");
    $rootScope.original_traffic_data = angular.copy($scope.traffic_data);
    $rootScope.original_total_data = angular.copy($scope.total_data);
    console.log($rootScope.original_traffic_data);
    console.log($rootScope.original_total_data);

    console.log("Variable data");
    console.log(total_data);
    console.log("=============");

enter image description here

The problem I am facing is that the

$rootscope.original_total_data

is not copying the contents of the

$scope.total_data

as seen on the screenshot. I have highlighted the different console logs to differentiate them from one another.

The line

console.log($rootScope.original_total_data);

shows no contents even though I have used angular.copy on that variable. What am I missing here? Please help. Thanks. Also $rootScope is already declared in the controller and it is working for the

$rootScope.original_traffic_data

so why is it not working for

$rootScope.original_total_data?

Thanks.

7
  • var copy = Object.assign({}, original). Copy function is not provided in Angular2. Commented Aug 9, 2017 at 17:02
  • @micronyks doesn't look like Angular2 Commented Aug 9, 2017 at 17:08
  • @Paul is total_data a valid JSON object? it doesn't look like it in the console output Commented Aug 9, 2017 at 17:09
  • @Ero. you are right ! No native copy function is avialable in Angular2 so far. Commented Aug 9, 2017 at 17:09
  • this is not angular 2 by the way. thanks for pointing that out too. Commented Aug 9, 2017 at 17:36

1 Answer 1

2

total_data is an array, whereas traffic_data is an object.

angular.copy() distinguishes between arrays and objects. For objects it will copy all the keys (properties). For arrays, it will only copy the array elements and not any custom properties attached to it - see source code.

If you want to set properties on total_data, you should make it into an object instead. It does not appear to have any indexed values, so this should not be a problem, and it probably should have been an object in the first place.

Sign up to request clarification or add additional context in comments.

2 Comments

ohh. ok. let me try that.
you're right. it should have been an object. thanks. Saved me a lot of time.

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.