How to route using ngRoute (with Demo)

2019-08-20 16:44发布

问题:

My code starts from here

<!DOCTYPE html>
<html>
<head>


<title>Routing</title>
</head>
<body ng-app="myApp">
<a href="#/login">Login</a>
<a href="#/register">Register</a>
<div ng-view></div>
</body>
<script src="angular-min.js" type="text/javascript"></script>
<script src="angular-route.js" type="text/javascript"></script>
<script>
        var app = angular.module("myApp", ["ngRoute"]);
        app.config(function($routeProvider) {
              $routeProvider

                  .when("/login", {
                           templateUrl : "login.html"
                           })
                  .when("/register", {
                         templateUrl : "register.html"
                           })                       
                });
</script>
</html>

I cannot route, it is simple touting with html, using simple method , the basic one , i do not know why it doesnt route

回答1:

This is with the version 1.2.

var app = angular.module("myApp", ["ngRoute"])
app.config(function($routeProvider) {
  $routeProvider.when('/', {
      template: `<h1>Login</h1>`,
      controller: 'loginCtrl'
    })
    .when('/register', {
      template: `<h1>Register</h1>`,
      controller: 'RegisterCtrl'
    })
    .otherwise({
      redirectTo: '/'
    });

});
app.controller('loginCtrl', function($scope) {
  $scope.name = "Login";

});
app.controller('RegisterCtrl', function($scope) {
  $scope.name = "Register";

})
<!DOCTYPE html>
<html ng-app="myApp">

<head>
  <meta charset="utf-8" />
  <title>AngularJS User Registration and Login Example  </title>
</head>

<body>
  <a href="#/login">Login</a>
  <a href="#/register">Register</a>
  <div class="mainContainer" ng-view></div>
  <script src="//code.angularjs.org/1.2.26/angular.js"></script>
  <script src="https://code.angularjs.org/1.2.26/angular-route.min.js"></script>
</body>

</html>

If you are using Angularjs version 1.6 and above, routes has changed. Look at this Answer