AngularJS 감청 경로 변화 방법

AngularJS 를 사용 할 때 경로 가 바 뀌 었 을 때 우 리 는 어떤 처 리 를 해 야 합 니 다.이 때 경로 사건 을 감청 할 수 있 습 니 다.$routeStartChange,$routeChange Success 를 자주 사용 합 니 다.전체 예 는 다음 과 같다.

<!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 입 니 다.Angular 2 도 사용 할 수 있 는 지,아직 시도 해 보지 않 았 습 니 다.검증 하고 기록 할 기회 가 있 습 니 다~
이상 이 바로 본 고의 모든 내용 입 니 다.여러분 의 학습 에 도움 이 되 고 저 희 를 많이 응원 해 주 셨 으 면 좋 겠 습 니 다.

좋은 웹페이지 즐겨찾기