如何在路线改变时观察/触发事件?
当前回答
$rootScope.$on( "$routeChangeStart", function(event, next, current) {
//if you want to interrupt going to another location.
event.preventDefault(); });
其他回答
$rootScope.$on( "$routeChangeStart", function(event, next, current) {
//if you want to interrupt going to another location.
event.preventDefault(); });
由于某种原因,建议的解决方案不适合我使用$routeChangeStart事件
如果你遇到同样的问题,试试:
$scope.$on('$stateChangeStart', function(evt, toState, toParams, fromState, fromParams) {
// ... you could trigger something here ...
});
在我的配置中,我使用了来自节点包管理器(npm)的@ui-router/angularjs (a.k.a angular-ui-router)
注意:这是AngularJS遗留版本的正确答案。有关更新版本,请参阅此问题。
$scope.$on('$routeChangeStart', function($event, next, current) {
// ... you could trigger something here ...
});
以下事件也可用(它们的回调函数采用不同的参数):
routeChangeSuccess美元 routeChangeError美元 $routeUpdate -如果reloadOnSearch属性已设置为false
参见$route文档。
还有另外两个未记录的事件:
locationChangeStart美元 locationChangeSuccess美元
查看$locationChangeSuccess和$locationChangeStart之间的区别是什么?
$rootScope.$on( "$routeChangeStart", function(event, next, current) {
//..do something
//event.stopPropagation(); //if you don't want event to bubble up
});
如果你不想把手表放在特定的控制器中,你可以在Angular的app run()中为整个应用程序添加手表。
var myApp = angular.module('myApp', []);
myApp.run(function($rootScope) {
$rootScope.$on("$locationChangeStart", function(event, next, current) {
// handle route changes
});
});
推荐文章
- 一元加/数字(x)和parseFloat(x)之间的区别是什么?
- angularjs中的compile函数和link函数有什么区别
- 删除绑定中添加的事件监听器
- 很好的初学者教程socket.io?
- HtmlSpecialChars在JavaScript中等价于什么?
- React: 'Redirect'没有从' React -router-dom'中导出
- 如何在React中使用钩子强制组件重新渲染?
- 我如何使用Jest模拟JavaScript的“窗口”对象?
- 我如何等待一个承诺完成之前返回一个函数的变量?
- 在JavaScript中根据键值查找和删除数组中的对象
- 使嵌套JavaScript对象平放/不平放的最快方法
- 如何以及为什么'a'['toUpperCase']()在JavaScript工作?
- 有Grunt生成index.html不同的设置
- 文档之间的区别。addEventListener和window。addEventListener?
- 如何检查动态附加的事件监听器是否存在?