How do I Redirect on the route if it is the first time it runs?

Asked

Viewed 191 times

0

My structure is like this:

var app = angular.module('MainApp',[
    'ngRoute',
    'mainAppControllers'
]);


app.config(['$routeProvider',

function($routeProvider){
    $routeProvider.
        when('/tutorial', {
            templateUrl: 'partials/tutorial.html',
            controller:  'TutorialCtrl'
        }).
        when('/menu', {
            templateUrl: 'partials/menu.html',
            controller:  'MenuCtrl'
        }).
        when('/termo', {
            templateUrl: 'partials/termo_de_uso.html',
            controller:  'TermoCtrl'
        }).
        otherwise({
            redirectTo : '/tutorial'
        }); 
}
]);

However I want when it is the first time you open the app it directs to a page and if it is the second time you open directs to another page.

How can I do that?

  • Your goal is to create something as if it were several stages?

  • Hi @Andréribeiro my idea is the first time you open the app it takes to a tutorial screen and after that the second time you open it take to another screen. The tutorial screen would only appear the first time you run the app

1 answer

2


You can store an entry in localStorage as soon as the tutorial controller is loaded and in function app.run() Angular you check if this entry exists and, if nay exists, you redirect to the tutorial route.

The function .run() is always called at module startup.

Ex.:

app.run(['$location', function($location){
  // tutorial foi visualizado? Se não (getItem() === null) redireciona pra rota do tutorial.
  if(window.localStorage.getItem("tutorial") === null) {
    $location.path('/tutorial');
  }
}]);

When loading TutorialController the entry is added.

app.controller('TutorialCtrl', ['$scope', function($scope){
    // ...
    window.localStorage.setItem("tutorial", 1);
    // ...
}]);

Remember to change the default route to something that don’t carry TutorialCtrl:

app.config(['$routeProvider',

    function($routeProvider){
        $routeProvider.
            when('/tutorial', {
                templateUrl: 'partials/tutorial.html',
                controller:  'TutorialCtrl'
            }).
            when('/menu', {
                templateUrl: 'partials/menu.html',
                controller:  'MenuCtrl'
            }).
            when('/termo', {
                templateUrl: 'partials/termo_de_uso.html',
                controller:  'TermoCtrl'
            }).
            otherwise({
                redirectTo : '/menu' // rota padrão que não seja a do tutorial
            }); 
    }
]);

That way the tutorial will always be loaded on first since the app runs regardless of the route that is accessed. In later uploads the operation will be normal.

  • Thank you very much! It worked perfectly

Browser other questions tagged

You are not signed in. Login or sign up in order to post.