AngularJS Routing Implementation Page Jump Example

  • 2021-07-26 06:23:16
  • OfStack

AngularJS is an javascript framework, and the popular single-page application can be realized through AngularJS class library. AngularJS also has the characteristics of bidirectional data binding, which is more suitable for dynamic content of pages.

The so-called single-page application is to dynamically load different contents on the same page, and the "jump" here can be understood as the jump of local pages.

AngularJS loads different page contents to specified locations by changing location addresses. The following is an example of simply applying AngularJS routing to realize page "jump":

Use app. config to define different location addresses to load different pages and have independent controllers;


var app = angular.module('MyApp', ['ngRoute']);
  app.config(function ($routeProvider) {
   $routeProvider
    .when('/', {  // '/' Represents the initial loading content of the page; 
     controller: 'homeCtrl', // Controller 
     templateUrl: '../view/home.html' // What to display 
    })
    .when('/reservation',{  // Indicates that the address ends with reservation Content loaded when; 
     controller: 'reservationCtrl',  
     templateUrl: '../view/reservation.html'
    })
  });

Use ng-view to define the location of dynamic content loading;


<!DOCTYPE html>
<html lang="en" ng-app="MyApp">
  <head>
    <script src="../angular.js"></script>
    <script src="../angular-route.min.js"></script>
  
    <script src="../js/main.js"></script>
    <script src="../js/homeController.js"></script>
    <script src="../js/reservationController.js"></script>

    <meta charset="UTF-8">
    <title></title>
  </head>
<body>
<div ng-view>
<!--  This is the dynamic loading area  -->
</div>
</body>
</html>

As mentioned above, each page will have an independent controller, and the functions in the controller will be executed while loading the page;


app.controller('homeCtrl',function($scope,$location){  // Page control function; 
  $scope.goToUrl=function(path) {    // This method can be changed location Address; 
    $location.path(path);
  }
});

The html page corresponding to the above controller is:


<div id="header">
  <p> Order a meal </p>
</div>
<div class="body">
  <button ng-click="goToUrl('/reservation')" class="bigButton"> Help order food </button>
  <button ng-click="goToUrl('/showList')" class="bigButton"> Look at the order </button>
</div>

The ng-click method executes the specified function method for the click event.


Related articles: