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

后端 未结 2 609
不思量自难忘°
不思量自难忘° 2020-12-15 11:41

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 lo

相关标签:
2条回答
  • 2020-12-15 12:10

    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.

    0 讨论(0)
  • 2020-12-15 12:20

    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>
    
    0 讨论(0)
提交回复
热议问题