带路由的自定义状态输入和状态退出代码

Naf*_*Kay 2 angularjs angularjs-routing

我有一个相当简单的Angular项目,它在JavaScript中路由到几个不同的URL:

function RootController($scope) {};

function PageOneController($scope) {};

angular.module('mymodule', []).config(
    ['$routeProvider', function($routeProvider) {
        $routeProvider.when('/', {
             templateUrl: "templates/root.html",
             controller: RootController
        }).when('/page1/', {
             templateUrl: "templates/page1.html",
             controller: PageOneController
        }).otherwise({redirectTo: '/'});
    }]
);
Run Code Online (Sandbox Code Playgroud)

到目前为止,一切都很好,但我确实需要一种方法,在输入和退出这些路径时运行一些JavaScript函数.即:

 $routeProvider.when('/', {
     templateUrl: "templates/root.html",
     controller: RootController,
     onenter: function() { console.log("Enter!"); },
     onexit: function() { console.log("Exit!"); }
 });
Run Code Online (Sandbox Code Playgroud)

有没有办法在Angular中做到这一点?在输入状态/路由时,我需要绑定事件侦听器,在退出时我需要销毁它们并拆除它们.

Cha*_*ani 5

$航线的有两个事件$routeChangeStart$routeChangeSuccess,这些可能是一些帮助你.

您可以$routeChangeStart在退出和$routeChangeSuccess进入之前使用.

您可以$scope.$on在任何控制器上观察这些事件.