Reputation: 938
I'm working on a two-page AngularJS app, where the user must complete the first page before moving on to the second page.
I have my $routeProvider setup as follows:
$routeProvider.
when('/config', {templateUrl: 'views/config.html', controller: ConfigController}).
when('/levels', {templateUrl: 'views/levels.html', controller: LevelsController}).
otherwise({redirectTo: '/config'});
So the user is initially sent to the Config page, and after filling in some fields, they press a button and are taken to the Levels page. The issue is that if they refresh the page while they are on the Levels page, I need them to be taken back to the Config page to fill in the fields again before they can come back to the Levels page.
Is there any way to achieve this?
Upvotes: 4
Views: 11877
Reputation: 40298
I have a similar use case: A wizard-style flow with 3 "pages"; the user fills in data in the 1st, then confirms the data in the 2nd and the 3rd displays the outcome.
Bookmarking the inner "pages" is meaningless: Unless the relevant data is filled-in the user must allways be redirected to the 1st page.
The way we solve these cases is not using routing; a single route houses all N pages under an ng-switch
:
<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>
And in the controller of the route:
angular.extend($scope, {
view: {
state: "dataEntry",
....
},
....
});
So whenever this controller is activated, the user will see the "dataEntry" screen. This, combined with some fancy animations, does the trick.
Alternative to ng-include
is a directive per inner page.
I don't have the code right now, but I think the HTML can be abbreviated to:
<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>
Upvotes: 1
Reputation: 4935
What you can do is to create a scope variable in your main controller and then check if this variable has been initialized or not.
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
}
}
And your html might be :
<body ng-app="MyApp">
<div ng-controller="MainCntl">
<div ng-view></div>
</div>
</body>
Upvotes: 2