-3

I have some basic angular code grabbing navigation menus for logged in and logged out users and storing the menus in $localStorage then toggling them to the $rootScope when the user logs in/out etc.

Below is a simplified version of that code for the purposes of this question.

It seems like one of the lines of code actually results the left-hand-side to be assigned to the right.

$localStorage.navigation = {};
$rootScope.nav = {};

// save the nav menus in local storage
$localStorage.navigation.loggedIn = "nav menu json";    

// use local storage to set the rootscope
$rootScope.nav = $localStorage.navigation;  

/*  should be..
    $rootScope.nav = {loggedIn:'nav menu json'};
    $localStorage.navigation = {loggedIn:'nav menu json'};
*/

// set the nav menu - Right-hand-assignment???
$rootScope.nav.current = $localStorage.navigation.loggedIn;

/*  should be..
    $rootScope.nav = { loggedIn:'nav menu json', current: 'nav menu json' };
    $localStorage.navigation = { loggedIn:'nav menu json' };
*/

console.log($rootScope.nav.current);    // 'nav menu json' as expected
console.log($localStorage.navigation.current);    // 'nav menu json', WHAT??!!

/*  actually..
    $rootScope.nav = { loggedIn:'nav menu json', current: 'nav menu json' };
    $localStorage.navigation = { loggedIn:'nav menu json', current: 'nav menu json' };
*/

What in the hell is happening here??

Emile Bergeron
  • 17,074
  • 5
  • 83
  • 129
yevg
  • 1,846
  • 9
  • 34
  • 70
  • 1
    This `$rootScope.nav = $localStorage.navigation;` is passing an object reference... overwriting the initial empty object. – Emile Bergeron Jun 16 '17 at 03:15

1 Answers1

3

Because $localStorage.navigation is an object not a primitive (Boolean, Number, String), this line assigns a reference, not a copy of $localStorage.navigation to $rootScope.nav:

$rootScope.nav = $localStorage.navigation;

At this point, $localStorage.navigation and $rootScope.nav are two references to exactly the same object. This line:

$rootScope.nav.current = $localStorage.navigation.loggedIn;

Is assigning the primitive value $localStorage.navigation.loggedIn to $rootScope.nav.current, but since $localStorage.navigation and $rootScope.nav are the exact same object, $localStorage.navigation.current refers to the same value as $rootScope.nav.current

To be clear, right-hand-side assignment is not possible.

bkbooth
  • 498
  • 3
  • 13