title: AngularJS | handle routing before they load
body: <p>I wish to create a simple authentication check for my routes by external service.</p>
  
  <p>I define the access requirements on the route object:</p>
  
  <pre><code>$routeProvider
      .when('/', {
          templateUrl: 'src/app/views/index.html',
          controller: 'indexCtrl',
          authenticated: true
      })
      .when('/login', {
          templateUrl: 'src/app/views/login.html',
          controller: 'loginCtrl',
          anonymous:  true
      })
      .otherwise({
          redirectTo: '/'
      })
  ;
  </code></pre>
  
  <p>Then, I check if I have permission within the <code>$routeChangeStart</code> event.</p>
  
  <pre><code>$rootScope.$on('$routeChangeStart', function (event, next) {
      if(next.authenticated &amp;&amp; !$myService.isLoggedin())
          $location.path("/login");
      else if(next.anonymous &amp;&amp; $myService.isLoggedin())
          $location.path("/secured");
  });
  </code></pre>
  
  <p>Actually, it works-<br />
  if the user in not authenticated it move him to the login page, if he is authenticated but the route is for anonymous users only it move them to another page, and etc..</p>
  
  <p><strong>BUT- this redirection actually happening after the controllers and the templates is load!</strong>
  And it cause my controller to do some unnecessary request to my REST API, even if I'm not authenticated.</p>
  
  <p>How can I handle the route before they process?</p>