【问题标题】:Redirect to a page on first load and after refresh首次加载和刷新后重定向到页面
【发布时间】:2013-09-15 18:11:26
【问题描述】:

我正在开发一个两页的 AngularJS 应用程序,用户必须先完成第一页,然后才能进入第二页。

我的 $routeProvider 设置如下:

$routeProvider.
        when('/config', {templateUrl: 'views/config.html', controller: ConfigController}).
        when('/levels', {templateUrl: 'views/levels.html', controller: LevelsController}).
        otherwise({redirectTo: '/config'});

因此,用户最初被发送到配置页面,在填写一些字段后,他们按下按钮并被带到级别页面。问题是,如果他们在“关卡”页面上刷新页面,我需要将他们带回“配置”页面以再次填写字段,然后他们才能返回“关卡”页面。

有什么办法可以做到吗?

【问题讨论】:

  • 你能组装一个plunk吗?
  • 你希望用户刷新时,他总是去第一页
  • 信息如何从第一页传递到第二页?我的意思是,除非加载了第一页,否则您不希望显示第二页 - 您如何或者更确切地说在哪里存储在第一页中输入的信息,以及如何与第二页共享这些信息?

标签: angularjs


【解决方案1】:

你可以做的是在你的主控制器中创建一个作用域变量,然后检查这个变量是否已经初始化。

angular.module('MyApp', [], function($routeProvider) {
$routeProvider.
        when('/config', {templateUrl: 'views/config.html', controller: ConfigController}).
        when('/levels', {templateUrl: 'views/levels.html', controller: LevelsController}).
        otherwise({redirectTo: '/config'});
});

function MainCntl($scope) {
  $scope.hasConfig = false;
}

function ConfigController($scope, $location) {
  // they press a button and are taken to the Levels page
  $scope.onSubmit = function () {
    $scope.hasConfig = true;
    $location.path('/levels');
  }
}

function LevelsController($scope, $location) {
  if($scope.hasConfig) {
    $location.path('/config');
  } else {
    //Stay on page
  }
}

你的 html 可能是:

<body ng-app="MyApp">
  <div ng-controller="MainCntl">
    <div ng-view></div>
  </div>
</body>

【讨论】:

  • 感谢您的建议,我最终选择了这个略有不同。我创建了一个工厂,它返回一个 config_completed 变量最初设置为 false 的对象,然后在我的 ConfigController 的提交中,我将其设置为 true,如果变量为 false,我在 LevelsController 的开头重定向到 Config 页面。跨度>
【解决方案2】:

我有一个类似的用例:带有 3 个“页面”的向导式流程;用户在1号填写数据,然后在2号确认数据,3号显示结果。

为内部“页面”添加书签是没有意义的:除非填写相关数据,否则用户必须始终重定向到第一页。

我们解决这些情况的方法是使用路由;单个路由包含ng-switch 下的所有 N 个页面:

<div ng-switch="view.state">
    <div ng-switch-when="dataEntry">
        <div ng-include="..."></div>
    </div>
    <div ng-switch-when="confirmation">
        <div ng-include="..."></div>
    </div>
    <div ng-switch-when="outcome">
        <div ng-include="..."></div>
    </div>
</div>

并且在路由的控制器中:

angular.extend($scope, {
    view: {
        state: "dataEntry",
        ....
    },
    ....
});

因此,每当激活此控制器时,用户都会看到“dataEntry”屏幕。这与一些花哨的动画相结合,就可以解决问题。

ng-include 的替代方案是每个内页的指令。


我现在没有代码,但我认为HTML可以缩写为:

<div ng-switch="view.state">
    <div ng-switch-when="dataEntry" ng-include="..."></div>
    <div ng-switch-when="confirmation" ng-include="..."></div>
    <div ng-switch-when="outcome" ng-include="..."></div>
</div>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-12-31
    • 2014-09-06
    • 2016-10-28
    • 1970-01-01
    • 1970-01-01
    • 2021-05-08
    • 1970-01-01
    相关资源
    最近更新 更多