Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
234 views
in Technique[技术] by (71.8m points)

javascript - AngularJS - Route to another page of different ng-app module after login

I have a basic knowledge of AngularJS only. I have created one AngularJS application.

index.html has two links for login and register. With ng-view. By default, login is the view. In the login view I have form. That will be posting to servlet and return the status with object. I have another page home.html wis=ch has its own ng-app module. When the login is success, I want to route to home.html pgae. It also has two links and one ng-view to display the links.

index.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <title>Login - AngularJS</title>

    <link rel="stylesheet" type="text/css" media="all" href="styles/angulardemo.css" />

    <script src="script/angular.min.js"></script>
    <script src="script/app.js"></script>
    <script src="script/loginController.js"></script>
  </head>

  <body data-ng-app="sampleApp">

    <div class="index container">
        <div class="row">
            <div class="">
                <ul class="nav">
                    <li><a href="#login"> Login </a></li>
                    <li><a href="#register"> View1 </a></li>
                </ul>
            </div>
            <div class="loginView">
                <div ng-view></div>
            </div>
        </div>
    </div>

  </body>
</html>

login.html

    <h2>Login</h2>

    <form ng-submit="loginUser()">
            <fieldset>
                <legend>Login</legend>

                <label>Name: </label> <input type="text" id="name" name="name"
                    ng-model="user.name" placeholder="User Name" required="required">
                    <br> <label>Password:</label> <input
                    type="password" id="password" name="password"
                    ng-model="user.password" placeholder="Your Password"
                    required="required"> <br>
                <button class="btn btn-primary">Login</button>
                <br />
            </fieldset>
            <label>{{user.status}}</label>
    </form>

app.js

//Define Routing for app
angular.module('sampleApp', []).config(['$routeProvider',
  function($routeProvider,$locationProvider) {
    $routeProvider
    .when('/login', {
        templateUrl: 'login.html',
        controller: 'LoginController'
    })
    .when('/register', {
        templateUrl: 'register.html',
        controller: 'RegisterController'
      })
      .otherwise({
        redirectTo: '/login'
      });
//    $locationProvider.html5Mode(true); //Remove the '#' from URL.
}]);

//Home Page Module
angular.module('homeApp', []).config(['$routeProvider',
function($routeProvider,$locationProvider) {
  $routeProvider
  .when('/home', {
      templateUrl: 'home.html'
  })
  .when('/profile', {
      templateUrl: 'profile.html',
      controller: 'ProfileController'
  })
  .when('/settings', {
      templateUrl: 'settings.html',
      controller: 'SettingsController'
    })
    .otherwise({
      redirectTo: '/home'
    });
//  $locationProvider.html5Mode(true);
}]);

LoginController (has both login and register. I have implemented only for login)

angular.module('sampleApp').controller('LoginController', function($scope,$location,$http) {
    $scope.user = {};
      $scope.loginUser = function() 
      {
        $http({
          method: 'POST',
          url: 'http://localhost:8080/AngularJSLogin/login',
          headers: {'Content-Type': 'application/json'},
          data:  $scope.user
        }).success(function (data) 
          {
            var strJSON=data;
            if(strJSON.status=="Success")
            {
                alert("success");
                $location.path( "/home" );
            }
            else
            {
                $scope.user.status=strJSON.userId+" : "+strJSON.status;
            }
          });
      };
});

angular.module('sampleApp').controller('RegisterController', function($scope,$location,$http) {
    $scope.user = {};
});

home.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <title>Login - AngularJS</title>

    <link rel="stylesheet" type="text/css" media="all" href="styles/angulardemo.css" />

    <script src="script/angular.min.js"></script>
    <script src="script/loginController.js"></script>
    <script src="script/userController.js"></script>
  </head>

  <body data-ng-app="homeApp">
    <div class="container">
        <div class="row homeTitle">
            <div class="username">
                <h3>{{user.name}}</h3>
            </div>
            <div class="homeMenu">
                <ul class="nav">
                    <li><a href="#profile"> Profile </a></li>
                    <li><a href="#settings"> Settings </a></li>
                </ul>
            </div>
        </div>
        <div class="">
            <div ng-view></div>
        </div>
    </div>

  </body>
</html>

Each link has its own controllers.

When I click on the login button with valid username and pasword, It is alerting with Success, but not going to the home (home.html) page.

How can I route to a different page that has different ng-app module from another one? And also how to pass this User object to home.html ng-app module, so it can have user data and display the user name, and other values?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I know this is over 2 years old and i'm sure you might have moved past this but i'm going to tell you how i did as i have a similar set up. Doing everything on the client side wont do it for you. You need to offload some of that routing logic to the server-side. Others might be suggesting using only one ng-app throughout your application but for me that was not a requirement. multi app was a necessity.

My application consisted of 6 ng-apps sharing some common modules and services. each with its own responsibility for e.g I had one like yours with views for login, signup and password-reset while the others were "protected ng-apps".

The trick to get mine working was with the login request. I dont return 200 json back on successful login from the server, I just redirect to the main page i.e I serve the protected main ng-app on successful login. Then i set a httpOnly Cookie with the user information serialized as a JWT String.

Point is...treat every angular application as one page and have your server-side code decide what to show based on your auth rules.

Hope this helps anyone using model :)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...