0

Due to the fact that it is used by multiple controllers, I have assigned data to $rootScope.currentCache. On initial load, that data looks (roughly) like this:

{
    System: "Foo Bar",
    StartDateTime: "2014-11-27T12:35:00"
}

(ignore formatting errors, they are irrelevant to the question).

In my (abridged) controller I run the following:

app.controller("CurrentController", function ($rootScope, $scope) {
    console.log($rootScope.currentCache);
    var currentData = $rootScope.currentCache;
    //processDate() converts StartDateTime into a friendly format
    currentData = processDate(currentData);
    console.log($rootScope.currentCache);
});

The first console.log() outputs the date as:

2014-11-27T12:35:00

However, the second console.log() outputs the date as:

Nov 27th 2014 at 12:35pm

This confuses me, as the date processing occurs on the separate currentData variable.

The other controllers need the date in the original format. So, my question is why is this happening, and how can I stop it?

sqdge
  • 43
  • 3

1 Answers1

0

It is not separate variable. both currentData and $rootScope.currentCache just point to real object { System: "Foo Bar", StartDateTime: "2014-11-27T12:35:00" }. So when u write currentData = {pit : 'isgood'} - this modifies only currentData. when u write currentData.System = 'foo2bar' - this modifies both. Try:

var currentDataDate = $rootScope.currentCache.StartDateTime;
currentDataDate = processDate(currentDataDate);
Petr Averyanov
  • 9,327
  • 3
  • 20
  • 38
  • While I didn't directly use this answer (my object was a lot more complex than described, and processing each individual element would not have been worthwhile). However, the idea that both variables point to the same object told me that cloning the original object would be the way forward. [This Article](http://stackoverflow.com/questions/13287297/duplicate-object-in-javascript) taught me how to do that. – sqdge Nov 14 '14 at 19:32