Redirection on `$stateChangeStart` with angularJS + ui.router
<p>Trying to redirect a user that is not authenticated to a login screen.</p>

<p>Im using <code>ui.route</code>r and a directive to check logged users. But its not working as i expected. Its not checking before the page loads and i get stuck on that page with continuous redirections.</p>

<p>Route config:</p>

<pre><code>//User profile
    .state('UserProfile', {
        url: "/u/:id",
        data: {
            restrict: true,
            name: "Your Profile",
            header: true,
            footer: false,
            css: true,
            transparentHeader: true
        },
        templateUrl: "app/partials/user/userProfile.html",
        controller: "userProfileController"
    })

//Login page for not authenticated users
    .state('LoginPage', {
        url: "/login/",
        data: {
            restrict: false,
            name: "Login",
            header: false,
            footer: false,
            css: false,
            transparentHeader: false
        },
        templateUrl: "app/partials/common/loginPage.html",
        controller: "loginController"
    })
</code></pre>

<p>service:</p>

<pre><code>.factory('userService', ['$cookies', function($cookies){

   var userData = {
        isLogged: false,
        userId: "",
        firstName: "",
        profilePic: ""
    };


    return userData;

}]);
</code></pre>

<p>Directive:</p>

<pre><code>socialMarkt.directive('checkUser', ['$rootScope', '$state', 'userService', function ($r, $state, userService) {
    return {
      link: function (scope, elem, attrs, ctrl) {
        $r.$on('$stateChangeStart', function(event, toState, toParams, fromState, fromParams, options){
          event.preventDefault();
          if($state.current.data.restrict){
            if(!userService.isLogged){
              $state.go('LoginPage');
            }
          }
        });
      }
    }
  }]);
</code></pre>

<p>i just added it to one page for testing. so if the user is not logged in, supposedly it would redirect to the login page using <code>$state.go('LoginPage')</code>.</p>