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?

1 Answer 1

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.

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

8 Comments

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.
You posted "It works when I log into the application for the first time"
Yes. But I am still confused as to why this is happening. What does being logged in have to do with scopes?
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.
Well, whatever you're doing to populate your commands isn't running when the page refreshes.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.