简体   繁体   中英

Load different templates and controllers in routes in Angular?

My app.js file looks like so:

angular.module('airline', ['ngRoute', 'airlineServices', 'ngCookies'])
    .config(airlineRouter);

function airlineRouter($routeProvider){
    $routeProvider
        .when('/', {
            templateUrl: 'partials/destinations.html',
            controller: 'DestinationsCtrl'
        })
        .when('/airports/:airportCode', {
            templateUrl: 'partials/airport.html',
            controller: 'AirportCtrl'
        })
        .when('/airports/:airport1/:airport2', {
            templateUrl: 'partials/two_airports.html',
            controller: 'TwoAirportsCtrl'
        })
        .when('/flights', {
            templateUrl: 'partials/flights.html',
            controller: 'FlightsCtrl'
        })
        .when('/reservations', {
            templateUrl: 'partials/reservations.html',
            controller: 'ReservationsCtrl'
        })
        .otherwise({
            redirectTo: '/'
        });
};

Now I simply wish that if the user is logged in, which I can easily try by sending a token from cookies to the server and getting a response, I wish to load a view and a controller, but if the user is not logged in, I just wish to load the login view and the login controller? How can configure the '/' route so that it loads different views and controllers?

The views are going to load dynamically, so you do not need to worry about them. The controller is part of your setup, so again, you do not need to worry about them. What you want to do is to display a view based on whether the user is authenticated or not.

When the user authenticates you want to setup a property somewhere, possibly in the $rootScope and then you can show different views, a code similar to below:

 <div data-ng-if="application.isAuthenticated()"> <div> I am logged in </div> </div> <div data-ng-if="!application.isAuthenticated()"> hello anon, please login. <button class="btn btn-primary" ng-click="application.login()">Login</button> </div> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM