title: Using $state methods with $stateChangeStart toState and fromState in Angular ui-router
body: <p>I'm writing a handler for <code>$stateChangeStart</code>:</p>
  
  <pre><code>var stateChangeStartHandler = function(e, toState, toParams, fromState, fromParams) {
      if (toState.includes('internal') &amp;&amp; !$cookies.MySession) {
          e.preventDefault();
          // Some login stuff.
      }
  };
  
  $rootScope.$on('$stateChangeStart', stateChangeStartHandler);
  </code></pre>
  
  <p><code>toState</code> does not have the includes method. Should I be doing something different, or is there a way to do what I'm trying to do?</p>
  
  <p>Also, when //some login stuff includes a <code>$state.go(...)</code>, I get an infinite loop. What might cause that?</p>
  
  <hr>
  
  <p>Here's a more complete example demonstrating what we eventually got to work:</p>
  
  <pre><code>angular.module('test', ['ui.router', 'ngCookies'])
  .config(['$stateProvider', '$cookiesProvider', function($stateProvider, $cookiesProvider) {
  
      $stateProvider
      .state('public', {
          abstract: true
      })
      .state('public.login', {
          url: '/login'
      })
      .state('tool', {
          abstract: true
      })
      .state('tool.suggestions', {
          url: '/suggestions'
      });
  
  }])
  .run(['$state', '$cookies', '$rootScope', function($state, $cookies, $rootScope) {
      $rootScope.$on('$stateChangeStart', function(e, toState, toParams, fromState, fromParams) {
  
          if (toState.name.indexOf('tool') &gt; -1 &amp;&amp; !$cookies.Session) {
              // If logged out and transitioning to a logged in page:
              e.preventDefault();
              $state.go('public.login');
          } else if (toState.name.indexOf('public') &gt; -1 &amp;&amp; $cookies.Session) {
              // If logged in and transitioning to a logged out page:
              e.preventDefault();
              $state.go('tool.suggestions');
          };
      });
  });
  </code></pre>
  
  <p>I don't like using <code>indexOf</code> to search for a particular state in the <code>toState</code>. It feels naive. I'm not sure why <code>toState</code> and <code>fromState</code> couldn't be an instance of the <code>$state</code> service, or why the <code>$state</code> service couldn't accept a state configuration override in its methods.</p>
  
  <p>The infinite looping was caused by a mistake on our part. I don't love this, so I'm still looking for better answers.</p>