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是否也可以用,还没尝试过,有机会验证了再记录下咯~~
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
上一篇: Angularjs根据json文件动态生成路由状态的实现方法
下一篇: Rhino试用记录