欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

AngularJS监听路由变化的方法

程序员文章站 2022-04-29 08:58:33
使用angularjs时,当路由发生改变时,我们需要做某些处理,此时可以监听路由事件,常用的是$routestartchange, $routechangesuccess。...

使用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">
   <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>在输入框中尝试输入:</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öp",
     "country" : "sweden"
    },{
     "name" : "centro comercial moctezuma",
     "country" : "mexico"
    },{
     "name" : "ernst handel",
     "country" : "austria"
    }]
  })    
  .controller('aboutcontroller', function ($scope) { 
   $scope.name = '呵呵';
  });
</script>  
</body>
</html>

上述的例子是angularjs 1的,对于angular2是否也可以用,还没尝试过,有机会验证了再记录下咯~~

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。