AngularJS routing


In this chapter we will introduce AngularJS routing to you.

AngularJS routing allows us to access different content through different URLs.

A multi-view single page web application (single page web application, SPA) can be implemented through AngularJS.

Usually our URL format is http://php.cn/first/page, but in single-page web applications AngularJS is implemented through # + tag , For example:

http://php.cn/#/first
http://php.cn/#/second
http://php.cn/#/third

When we click on any of the above links, the address requested from the server is the same (http://php.cn/). Because the content after the # sign will be ignored by the browser when requesting the server. So we need to implement the functionality behind the # number on the client. AngularJS routing uses # + tag to help us distinguish different logical pages and bind different pages to the corresponding controllers.

angular-routing.png

In the above graphic, we can see that two URLs are created: /ShowOrders and /AddNewOrder. Each URL has a corresponding view and controller.

Next let’s look at a simple example:

Instance

<html>
    <head>
    	<meta charset="utf-8">
        <title>AngularJS 路由实例 - 菜鸟教程</title>
    </head>
    <body ng-app='routingDemoApp'>
     
        <h2>AngularJS 路由应用</h2>
        <ul>
            <li><a href="#/">首页</a></li>
            <li><a href="#/computers">电脑</a></li>
            <li><a href="#/printers">打印机</a></li>
            <li><a href="#/blabla">其他</a></li>
        </ul>
         
        <div ng-view></div>
        <script src="//cdn.bootcss.com/angular.js/1.4.6/angular-animate.min.js"></script>
        <script src="//cdn.bootcss.com/angular.js/1.3.13/angular-route.js"></script>
        <script>
            angular.module('routingDemoApp',['ngRoute'])
            .config(['$routeProvider', function($routeProvider){
                $routeProvider
                .when('/',{template:'这是首页页面'})
                .when('/computers',{template:'这是电脑分类页面'})
                .when('/printers',{template:'这是打印机页面'})
                .otherwise({redirectTo:'/'});
            }]);
        </script>
     
     
    </body>
</html>

Running Example»

Click the "Run Instance" button to view the online instance

Example analysis:

  • #1. Load the js file that implements routing: angular-route.js.

  • 2. Contains the ngRoute module as a dependent module of the main application module.

    angular.module('routingDemoApp',['ngRoute'])
  • 3. Use the ngView command.

    <div ng-view></div>

    The HTML content within this div will change according to the routing changes.

  • Configure $routeProvider, AngularJS $routeProvider is used to define routing rules.

    module.config(['$routeProvider', function($routeProvider){
        $routeProvider
            .when('/',{template:'这是首页页面'})
            .when('/computers',{template:'这是电脑分类页面'})
            .when('/printers',{template:'这是打印机页面'})
            .otherwise({redirectTo:'/'});
    }]);

    The config function of the AngularJS module is used to configure routing rules. By using configAPI, we request $routeProvider is injected into our configuration function and use $routeProvider.whenAPI to define our routing rules.

    $routeProvider provides us with the when(path,object) & otherwise(object) function to define all routes in order. The function contains two parameters:

    • The first parameter is the URL or URL regular rule.

    • The second parameter is the routing configuration object.


    Route setting object

    AngularJS routing can also be implemented through different templates.

  • The first parameter of the $routeProvider.when function is the URL or URL regular rule, and the second parameter is the routing configuration object.


  • The routing configuration object syntax rules are as follows:

    $routeProvider.when(url, {
        template: string,
        templateUrl: string,
        controller: string, function 或 array,
        controllerAs: string,
        redirectTo: string, function,
        resolve: object<key, function>
    });

    Parameter description:

    • template:

      If we only need to insert simple HTML content into ng-view, use this parameter:

      .when('/computers',{template:'这是电脑分类页面'})

    • templateUrl:

      If we only need to insert the HTML template file in ng-view, use this parameter:

      $routeProvider.when('/computers', {
          templateUrl: 'views/computers.html',
      });

      Above The code will get the contents of the views/computers.html file from the server and insert it into ng-view.


    • controller:

      function, string or array type, in the current The controller function executed on the template generates a new scope.


    • controllerAs:

      #string type, specifies an alias for the controller.


    • redirectTo:

      The redirected address.


    • resolve:

      Specify other modules that the current controller depends on.


    • ##Instance

      <html>
      <head>
      <meta http-equiv="content-type" content="text/html; charset=UTF-8">
      <script src="http://apps.bdimg.com/libs/angular.js/1.4.6/angular.min.js"></script>
      <script src="http://apps.bdimg.com/libs/angular-route/1.3.13/angular-route.js"></script>
      
      <script type="text/javascript">
      angular.module('ngRouteExample', ['ngRoute'])
      .controller('HomeController', function ($scope) { $scope.$route = $route;})
      .controller('AboutController', function ($scope) { $scope.$route = $route;})
      .config(function ($routeProvider) {
          $routeProvider.
          when('/home', {
              templateUrl: 'embedded.home.html',
              controller: 'HomeController'
          }).
          when('/about', {
              templateUrl: 'embedded.about.html',
              controller: 'AboutController'
          }).
          otherwise({
              redirectTo: '/home'
          });
      });
      </script>
      
        
      </head>
      
      <body ng-app="ngRouteExample" class="ng-scope">
        <script type="text/ng-template" id="embedded.home.html">
            <h1> Home </h1>
        </script>
      
        <script type="text/ng-template" id="embedded.about.html">
            <h1> About </h1>
        </script>
      
        <div> 
          <div id="navigation">  
            <a href="#/home">Home</a>
            <a href="#/about">About</a>
          </div>
            
          <div ng-view="">
          </div>
        </div>
      </body>
      </html>

      Running Instance» Click the "Run Instance" button to view the online instance