Search code examples
angularjsangularjs-scopeangular-ui-router

How to prevent the execution of controller upon calling state.go in an if condition?


I am trying to check for a condition in controller and redirect to a different state. But the code after calling State.go is executing as well. The problem I am dealing with is that when I refresh the page using F5, the event beforeunload fires and prompt for user to choose between 'Leave this page' and 'Stay on this page'. If I choose 'Stay on this page', it leaves the page as is and it looks good. But if I choose 'Leave this page', it tries to reload the page so I am trying to redirect to a different state upon missing some data.

var windowElement = angular.element($window);
      windowElement.on('beforeunload', function (event) {

          console.log('refreshing the page');
          var path = $location.path();

          if (path == '/record' || path == '/recordcreated') {
              event.preventDefault();
          }
      });

      $scope.$on('$stateChangeStart', function (event, toState, toParams, fromState, fromParams, options) {
          //Do not allow to go from record created page to record page.
          if (fromState.name == 'recordcreated' && toState.name == 'record') {
              event.preventDefault();
              $state.go('home');
          }
      });

      $scope.selectedRecord = service.GetSelectedRecord();
       //Check if null and redirect to home state
      if ($scope.selectedRecord == null)
      {
          $state.go('home', {}, { reload: true });
      }

      //Continuing to execute this line
      $scope.Balance = service.GetBalance();

How can I make it stop executing the above line after calling state.go ? Thanks for any suggestions.


Solution

  • Two ways to achieve this:

    Add the keyword return to the line you wish the code to stop executing at:

    return $state.go('home', {}, { reload: true });
    

    Or, append your if statement with an else block:

    if ($scope.selectedRecord == null) {
        $state.go('home', {}, { reload: true });
    } else {
        //Continuing to execute this line
        $scope.Balance = service.GetBalance();
    }