ui-router $state.go() to sibling using onEnter

by klode

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.15/angular-ui-router.js"></script>
<p>In this jsfiddle state "root.app.pivot" is landing page that redirects to root.app.a or root.app.b
</p>
<p>When can see that the first time, "root" and "root.app" revolve method are triggered twice</p>
<p>and that when clicking on "page b" link a <span class="error">Error: null is not an object (evaluating '$state.$current.locals[name]')</span> occurs
</p>
<hr />
<div ng-app="myApp">
  <ui-view name="header"></ui-view>
  <ui-view name="content"></ui-view>
  <ui-view name="footer"></ui-view>
</div>

CSS

.error {
  color: red;
}

p {
  margin: 0;
  padding: 0;
}

JavaScript

angular.module('myApp', ['ui.router'])
  .factory('authService', ['$timeout', '$q',
    function($timeout, $q) {
      var service = {
        currentUser: null,
        userPromise: null,
        requestUser: function() {
          if (!service.userPromise) {
            service.userPromise = $q.defer();
            $timeout(function() {
              var user = {
                type: 1
              };
              console.log('fetching User');
              service.userPromise.resolve(user);
              service.currentUser = user;
            }, 100);
          }

          return service.userPromise;
        }
      };
      return service;
    }
  ])
  .config(['$stateProvider', '$urlRouterProvider',
    function($stateProvider, $urlRouterProvider) {
      $urlRouterProvider.otherwise("/?page=a");
      $stateProvider
        .state('root', {
          url: '',
          abstract: true,
          resolve: {
            user: function(authService) {
              return authService.requestUser();
            }
          },
          views: {
            'footer@': {
              template: '<h1>======= FOOTER ===========</h1>',
            }
          }
        })
        .state('dashboard', {
          parent: 'root',
          url: '/',
          onEnter: ['$state', function($state, authService) {
            console.log('redirectTo');
            if (authService.currentUser.type === 1) {
              $state.go('student');
            }
            if (authService.currentUser.type === 2) {
              $state.go('teacher');
            }
            // TODO create some public landing page to redirect-to as default
          }]
        })
        .state('student', {
          parent: 'root',
          url: '/student',
          views: {
            'header@': {
              template: '<a ui-sref="dashboard">DASHBOARD</a> <a ui-sref="student.profile">PROFILE</a>'
            },
            'content@': {
              template: '<h1> === STUDENT HOME...