问题解答html
angular1项目导入ui-router以后,使用路由监听,代码以下git
angular.module("app") .run(['$rootScope', function ($rootScope) { // 监听路由开始时触发 $rootScope.$on('$stateChangeStart', function () {} // 监听路由成功时触发 $rootScope.$on('$stateChangeSuccess', function () {} // 监听路由出现错误时触发 $rootScope.$on('$stateChangeStart', function () {} }) }])
当切换路由的时候,本来应该会监听到路由的变化,可是实际却没有走这个路由监听器,这是为何呢?答案以下:github
这时须要在index.html导入一个stateEvents.js库文件,解决路由监听不到的问题(PS:必须在angular.module主模块下注入'ui.router.state.events')app
附上ui-router官方教程地址:https://ui-router.github.io/ng1/ui
附上stateEvents.js官方教程地址:https://ui-router.github.io/ng1/docs/latest/modules/ng1_state_events.html#_statechangeerrorurl
参数解读spa
根据stateEvents.js官方教程地址,路由监听提供的参数部分翻译翻译
event: 该事件的基本信息code
toState: 获得当前路由的信息,好比路由名称,url,视图的控制器,模板路径等router
toParams: 获得当前路由的参数
fromState: 获得上一个路由的信息,好比路由名称,url,视图的控制器,模板路径等
fromParams:获得上一个路由的参数
后记
若有不对的地方,还望你们指正,共同进步