How do I make a Redirect on the route if it's the first time it runs?

0

My structure looks 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 it when it first opens the app it directs to a page and if it is the second time it opens it directs to another page.

How can I do this?

    
asked by anonymous 23.01.2015 / 21:04

1 answer

2

You can store an entry in localStorage once the tutorial controller loads and in the app.run() of the Angular function you check if this entry exists and, if does not exist, you redirect tutorial route.

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

Eg:

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 you load TutorialController the entry is added.

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

Remember to change the default route to something do not load 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
            }); 
    }
]);

In this way the tutorial will always be loaded in the first time the app runs regardless of which route is accessed. On subsequent uploads the operation will be normal.

    
26.01.2015 / 02:20