温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

AngularJS如何监听路由变化

发布时间:2021-07-28 09:11:40 来源:亿速云 阅读:377 作者:小新 栏目:web开发

这篇文章将为大家详细讲解有关AngularJS如何监听路由变化,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。

使用AngularJS时,当路由发生改变时,我们需要做某些处理,此时可以监听路由事件,常用的是$routeStartChange, $routeChangeSuccess。完整例子如下:

<!DOCTYPE html>
<html>
<head>
 <meta charset="utf-8">
 <meta http-equiv="X-UA-Compatible" content="IE=edge">
 <title>AngularJS监听路由变化</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">
   <h2> Home </h2>
   <table>
    <tbody>
     <tr ng-repeat="x in records" >
      <td>{{x.Name}}</td>
      <td>{{x.Country}}</td> 
     </tr>     
    </tbody>
   </table>
  </script>

  <script type="text/ng-template" id="about.html">
   <h2> About </h2>
   <p>在输入框中尝试输入:</p>
   <p>姓名:<input type="text" ng-model="name"></p>
   <p>你输入的为: {{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) {
    /* 监听路由的状态变化 */
    $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&ouml;p",
     "Country" : "Sweden"
    },{
     "Name" : "Centro comercial Moctezuma",
     "Country" : "Mexico"
    },{
     "Name" : "Ernst Handel",
     "Country" : "Austria"
    }]
  })    
  .controller('AboutController', function ($scope) { 
   $scope.name = '呵呵';
  });
</script>  
</body>
</html>

关于“AngularJS如何监听路由变化”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,使各位可以学到更多知识,如果觉得文章不错,请把它分享出去让更多的人看到。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI