Method for AngularJS to Monitor Route Change

  • 2021-07-26 06:40:45
  • OfStack

When using AngularJS, we need to do some processing when the route changes. At this time, we can listen for routing events, which are commonly used as $routeStartChange and $routeChangeSuccess. A complete example is as follows:


<!DOCTYPE html>
<html>
<head>
 <meta charset="utf-8">
 <meta http-equiv="X-UA-Compatible" content="IE=edge">
 <title>AngularJS Listen for routing changes </title>
</head>
<body ng-app="ngRouteExample">
  <div id="navigation"> 
   <a href="#/home" rel="external nofollow" >Home</a>
   <a href="#/about" rel="external nofollow" >About</a>
  </div>
   
  <div ng-view></div>

  <script type="text/ng-template" id="home.html">
   <h1> Home </h1>
   <table>
    <tbody>
     <tr ng-repeat="x in records" style="background:#abcdef;">
      <td>{{x.Name}}</td>
      <td>{{x.Country}}</td> 
     </tr>     
    </tbody>
   </table>
  </script>

  <script type="text/ng-template" id="about.html">
   <h1> About </h1>
   <p> Try to enter in the input box: </p>
   <p> Name: <input type="text" ng-model="name"></p>
   <p> What you entered is:  {{name}}</p>
  </script>

  <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'])
  .config(function ($routeProvider) {
    $routeProvider.
    when('/home', {
      templateUrl: 'home.html',
      controller: 'HomeController'
    }).
    when('/about', {
      templateUrl: 'about.html',
      controller: 'AboutController'
    }).
    otherwise({
      redirectTo: '/home'
    });
  })
  .run(['$rootScope', '$location', function($rootScope, $location) {
    /*  Listen for changes in the state of a route  */
    $rootScope.$on('$routeChangeStart', function(evt, next, current){
     console.log('route begin change');
    }); 
    $rootScope.$on('$routeChangeSuccess', function(evt, current, previous) {
     console.log('route have already changed  : '+$location.path());
    }); 
  }])
  .controller('HomeController', function ($scope) { 
    $scope.records = [{
     "Name" : "Alfreds Futterkiste",
     "Country" : "Germany"
    },{
     "Name" : "Berglunds snabbköp",
     "Country" : "Sweden"
    },{
     "Name" : "Centro comercial Moctezuma",
     "Country" : "Mexico"
    },{
     "Name" : "Ernst Handel",
     "Country" : "Austria"
    }]
  })    
  .controller('AboutController', function ($scope) { 
   $scope.name = ' Hehe ';
  });
</script>  
</body>
</html>

The above example is AngularJS 1. Whether Angular2 can also be used, I haven't tried it yet. I have the opportunity to verify it and record it again ~ ~


Related articles: