Kent Weigel Kent Weigel - 17 days ago 5
Javascript Question

Clear shared AngularJS controller variable when ui-router state changes

In an AngularJS 1.5.8 app, I am using ui-router to navigate between pages which all use the same controller. The ng-controller attribute is applied to the body tag, and the ui-view attribute is applied to a div which is obviously inside the body of the HTML. For simplicity sake, let's say it looks like this:

<body ng-controller="SecurityController as securityCtrl">
<div ui-view></div>

An example route, in case that helps to visualize what I am saying, is:

.state('login', {
url: "/login/:returnState",
templateUrl: "Account/Login"

The routing is working fine, and when I change states it is not re-initializing the controller, which is what I want. I have an
variable in the controller which I would like to set to undefined whenever the state changes, but I'd rather not add javascript to the navigation buttons to make that happen.

I know that you can register event handlers for routing, and I am successfully using them for
, but the parameters which are available are
event, toState, toParams, fromState, fromParams, and error
. I don't see how I could easily use these, without a big
statement, to tell the common controller to set its
variable to undefined. Not all routes need to clear out this variable, but I suppose I could just clear it whether doing so is necessary or not.

Also, I heard somewhere that you can make the controller re-initialize after each state change. That is plan B or C.

What is the simplest way of marking a subset of the routes in a way that I could easily determine whether the fromState or toState is marked in this way, so that I can clear the variable? If you can think of a better (still DRY) way to do this, I'm all ears.

.state('someState', {
    url: "/somestate",
    data: { resetMessage: true } 

And in your .run

$rootScope.$on('$stateChangeStart', function(event, toState, toParams, fromState, fromParams) {
  if (
     ... //Clear errorMessageVariable