Detecting route changes in AngularJS

Working with AngularJS there are cases where you want to execute code in a controller when the user clicks a link and the route changes.

In the following I’m triggering a new search based on querystring parameters.

function TenantsCtrl($scope, $http, $routeParams, $location, fetchFinancialService) {
    $scope.$on('$routeChangeSuccess', function () {
        if (typeof $routeParams.startDate === "undefined" || typeof $routeParams.endDate === "undefined") {
            $scope.startDate = "01-01-2000";
            $scope.endDate = "31-12-" + new Date().getFullYear();
        } else {
            $scope.startDate = $routeParams.startDate;
            $scope.endDate = $routeParams.endDate;

    fetchFinancialService.fetchTenants($scope, $http, $routeParams);

Please notice that it is the $routeChangeSuccess-event that I utilize for this purpose.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s