I'd like to know the best practice, how to set up routing and templates in AngularJS to show a different front & login area to visitors, and then show a dashboard to logged in users on the same base url ('/').
The two pages are structurally completely different, and also different assets are needed.
Is it better to setup two different apps for the 2 parts of the website, but then how would I manage the session between the 2?
Or is it better to make an "empty" layout with nothing between the body tags an load the different templates into that, and make separate routing for the front part and the dasboard part?
I'm looking for kind of like the way Facebook's login is made. To stay on the root domain after logging in.
I spent my afternoon Googling and searching SO, but couldn't find any guides on this. Any ideas how you usually do this kind of separation in AngularJS would be very welcome.
Martin's answer is fine, but I'd rather solve the problem with ui-router module:
root
, dashboard
and landing
.root
state and redirect to dashboard
or landing
depending on authorization status.dashboard
and landing
will have controller
and templateUrl
defined in one place together with other application states, which is nice.Code example:
angular
.module("app", ["ui.router"])
.value("user", {
name: "Bob",
id: 1,
loggedIn: true
})
.config(function($stateProvider) {
$stateProvider
.state("root", {
url: "",
template: "<section ui-view></section>",
controller: function($state, user) {
if ($state.is("root")) $state.go(user.loggedIn ? "dashboard" : "landing");
}
})
.state("landing", {
templateUrl: "landing.html",
controller: "LandingCtrl"
})
.state("dashboard", {
templateUrl: "dashboard.html",
controller: "DashboardCtrl"
});
})
.controller("DashboardCtrl", function($scope, user, $state) {
$scope.logout = function() {
user.loggedIn = false;
$state.go("root");
}
})
.controller("LandingCtrl", function($scope, user, $state) {
$scope.login = function() {
user.loggedIn = true;
$state.go("root");
}
})
Complete example on Plunker.
You can use the same master template, include different partials depending on if the user is logged in or not.
<ng-include=" 'views/loggedout.html' " ng-if="!loggedIn"></ng-include>
<ng-include=" 'views/loggedin.html' " ng-if="loggedIn"></ng-include>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With