您好,登錄后才能下訂單哦!
這篇文章將為大家詳細講解有關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öp", "Country" : "Sweden" },{ "Name" : "Centro comercial Moctezuma", "Country" : "Mexico" },{ "Name" : "Ernst Handel", "Country" : "Austria" }] }) .controller('AboutController', function ($scope) { $scope.name = '呵呵'; }); </script> </body> </html>
關于“AngularJS如何監聽路由變化”這篇文章就分享到這里了,希望以上內容可以對大家有一定的幫助,使各位可以學到更多知識,如果覺得文章不錯,請把它分享出去讓更多的人看到。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。