简体   繁体   中英

Url changed but nothing shows up in AngularJS

I have a login page, and a home page and the way I am implementing them is that each has its own module. Login page has loginApp and home page has myApp. When I click the submit, I want to navigate to home.html.

In my index.html(login page), I have this:

   <script>
     angular.module("whole", ["loginApp", "myApp"]);
   </script>

And at top I declared this:

<html ng-app="whole" class="ng-scope">

Now I am stuck at this ngRoute. I have this:

"use strict";
var lapp = angular.module("loginApp", ["ngRoute", "ngCookies"]);

lapp.config(["$routeProvider", function ($routeProvider) {
    $routeProvider
            .when("/", {
                templateUrl: "index.html"
            })
            .when("/home", {
                templateUrl: "home.html"
            })
            .otherwise({redirectTo: '/'});
}]);

and this in my loginCtrl:

$scope.login = function () {
        var credentials = {
            username: $scope.username,
            password: $scope.password
        };
        Auth.login(credentials, function (res) {
            init();
            $location.path("views/home.html");
        }, function (err) {
            init();
        });

and this in my html:

<div ng-controller="loginCtrl" class="login">
  <form ng-submit="login()" method="post" name="form" novalidate>  
   <!--two inputs and stuff-->
   <input type="submit" value="Login">
 <!--Then some closing tags, whatever-->

My initial url is :

http://localhost:8000/public_html/

after I click submit(login), it changes to

http://localhost:8000/public_html/views/home.html#/basic

but then the view doesn't change unless I refresh the page. There was another post about this but he did a typo and I am sure I did type "templateUrl" correctly. I do not even have an idea about what might have caused this bug. I just assumed ngRoute.

You're missusing the '.otherwise'

You need to seperate the understanding between a templateUrl to path.

A template url is a url points on an html file that will get injected into the ng-view directive

A path is your surfix of the url telling your router which templateUrl (and other configs) should be used

For example:

App config block:

$routeProvider
   .when("/login", {
         templateUrl: "login.html"
     })
   .when("/home", {
         templateUrl: "home.html"
     })
     .otherwise({redirectTo: '/home'}); <-- if no path is matched, use this path 

Controller:

  $scope.login = function () {
    var credentials = {
        username: $scope.username,
        password: $scope.password
    };

    Auth.login(credentials, function (res) {
        init();
        $location.path("/home");
    }, function (err) {
        init();
    });

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