AngularJS,钩子URL更改
我有AngularJS应用程序和下一条路线:AngularJS,钩子URL更改,angularjs,Angularjs,我有AngularJS应用程序和下一条路线: /user/:userId 用户打开 http://localhost/#/user/1 在浏览器中。然后他在URL栏中将userId值从1更改为2,然后按enter键 我的问题是:如何钩住这一刻而不重新加载控制器?例如,我只想在同一页上用新的用户ID值显示消息(或执行alert()或console.log())。您可以侦听并调用事件。preventDefault(),以防止用户实际转到新视图 $rootScope.$on('$stateChan
/user/:userId
用户打开
http://localhost/#/user/1
在浏览器中。然后他在URL栏中将userId
值从1
更改为2
,然后按enter键
我的问题是:如何钩住这一刻而不重新加载控制器?例如,我只想在同一页上用新的用户ID
值显示消息(或执行alert()或console.log())。您可以侦听并调用事件。preventDefault()
,以防止用户实际转到新视图
$rootScope.$on('$stateChangeStart',
function(event, toState, toParams, fromState, fromParams){
event.preventDefault();
// transitionTo() promise will be rejected with
// a 'transition prevented' error
});
注意,如果要在控制器中添加此侦听器,则应保留对注销函数的引用,以便在范围被破坏时删除该侦听器
var removeListenerFn = $rootScope.$on('$stateChangeStart',
function(event, toState, toParams, fromState, fromParams){
event.preventDefault();
// transitionTo() promise will be rejected with
// a 'transition prevented' error
}
);
$scope.$on('$destroy',function(){
removeListenerFn();
});
下面是一个示例Plunker,您可以使用它进行测试: