Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

same url ('/') with different templates based on login status in AngularJS

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.

like image 559
Jack Gerson Avatar asked Sep 05 '14 14:09

Jack Gerson


2 Answers

Martin's answer is fine, but I'd rather solve the problem with ui-router module:

  1. Create three states: root, dashboard and landing.
  2. Capture URL with root state and redirect to dashboard or landing depending on authorization status.
  3. 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.

like image 101
Klaster_1 Avatar answered Sep 19 '22 16:09

Klaster_1


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>
like image 32
Martin Avatar answered Sep 16 '22 16:09

Martin