【问题标题】:How to prevent the execution of controller upon calling state.go in an if condition?如何防止在 if 条件下调用 state.go 时执行控制器?
【发布时间】:2017-01-20 03:35:06
【问题描述】:

我正在尝试检查控制器中的条件并重定向到不同的状态。但是调用 State.go 之后的代码也在执行。我正在处理的问题是,当我使用 F5 刷新页面时,会触发 beforeunload 事件并提示用户在“离开此页面”和“留在此页面上”之间进行选择。如果我选择“留在此页面上”,它将保持页面不变并且看起来不错。但是,如果我选择“离开此页面”,它会尝试重新加载页面,因此我会尝试在丢失某些数据时重定向到不同的状态。

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();

如何在调用 state.go 后让它停止执行上述行?感谢您的任何建议。

【问题讨论】:

    标签: angularjs angularjs-scope angular-ui-router


    【解决方案1】:

    实现这一点的两种方法:

    将关键字 return 添加到您希望代码停止执行的行:

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

    或者,将 if 语句附加到 else 块:

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

    【讨论】:

    • 非常感谢。回报工作非常整洁。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-19
    • 2014-01-23
    • 1970-01-01
    • 2015-01-14
    • 2022-08-16
    相关资源
    最近更新 更多