2

I have a fairly simple Angular project which routes to a couple different URLs in the JavaScript:

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: '/'});
    }]
);

Everything works great so far, but I do need a way to have some JavaScript function run on when these routes are entered and exited. ie:

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

Is there a way to do this in Angular? On enter of a state/route, I need to bind event listeners, and on exit I need to destroy them and tear down.

4

1 回答 1

5

$route service has two events $routeChangeStart and $routeChangeSuccess, these can be of some help for you.

You can use $routeChangeStart before exiting and $routeChangeSuccess on entering.

You can do $scope.$on on any controller to watch for these events.

于 2013-08-16T17:26:20.893 回答