1

I have the following piece of code in Angular:

  $rootScope.commands.forEach(function(element, index, array){
            commands[element] = function() {alert(element + " Test Command!");}
  });

It works when I log into the application for the first time. That is, if I inspect the commands JSON object, it contains entries from $rootScope.commands.

The problem comes in when I refresh the page. It is then that I get the error that $rootScope.commands is undefined.

Why is this happening? Clearly, there is a difference in behavior between logging in the first time and just refreshing the page.

Any ideas?

MadPhysicist
  • 5,401
  • 11
  • 42
  • 107

1 Answers1

1

When you login, I'm assuming you're setting $rootScope.commands. When you're refreshing, you're no longer calling this login code anymore (As you're already logged in). Anything that's set in javascript variables will simply be destroyed when the page reloads, and will have to be reset through initialization functions.

My recommendation: Add some startup code, using angular.module('your_module_name').run(), and check if the user is logged in. If they are, build $rootScope.commands again.

Blue
  • 22,608
  • 7
  • 62
  • 92
  • This is not as much about login in (at least it seems like it to me). I have a controller which is invoked when the route is "/" and sets `$rootScope.commands=[]` I then populate the actual entries in a different (I assume) child controller. That is, I assume that "HomeCtrl" is the highest level as it is called on `app.config` before other controllers declared within that `home.html` partial. – MadPhysicist Jul 30 '16 at 20:15
  • 1
    You posted "It works when I log into the application for the first time" – Blue Jul 30 '16 at 20:18
  • Yes. But I am still confused as to why this is happening. What does being logged in have to do with scopes? – MadPhysicist Jul 30 '16 at 20:19
  • You're entire app, scopes, everything are destroyed when the page refreshes. They're all stored in variables within javascript, that will not live through a page reload. You'll have to rebuild everything again when the scope loads. – Blue Jul 30 '16 at 20:40
  • That is what I was surmising. However, still, how is that different from login in anew? Is going to route "/" equivalent to hitting a refresh on that same route? – MadPhysicist Jul 30 '16 at 20:50
  • 1
    Well, whatever you're doing to populate your commands isn't running when the page refreshes. – Blue Jul 30 '16 at 20:57
  • Yes, that much is clear. So, what does the `module.run()` do? Runs whenever there is a fresh start or refresh? – MadPhysicist Jul 30 '16 at 20:59
  • See the module documentation [here](https://docs.angularjs.org/guide/module): Run blocks - get executed after the injector is created and are used to kickstart the application. Only instances and constants can be injected into run blocks. This is to prevent further system configuration during application run time. – Blue Jul 30 '16 at 21:01