运行 每次导航到 angular 路由时的函数

Run a function every time an angular route is navigated to

每次 Angular 路由导航到时,我都想 运行 一个函数。

一个选项是我只将 myFunction() 添加到每个控制器的顶部。看起来真的很重复。每次 $location 更改时,有没有更好的方法 运行 myFunction()

如果您正在使用 ui-router,您可以简单地将函数绑定到 $rootscope。 请参阅 stateChange 部分:https://github.com/angular-ui/ui-router/wiki#state-change-events

    $rootScope.$on('$stateChangeSuccess', 
    function(event, toState, toParams, fromState, fromParams){ ... })