Darwin Tech
Darwin Tech

Reputation: 18919

Angular getting access to $routeParams in a controller not connected to the route

I have a SPA Angular app which has two main html divs. One of these changes frequently and the other less frequently. The frequently changing one uses $route in the app.config. The less frequently changing div also needs to be aware of url changes, so I want to listen for changes in $routeParamas and do stuff accordingly.

So in my controller I have:

 .controller('SecondaryCtrl', function ($scope, $routeParams, MyService) {

     $scope.$watch('routeParams', function () {
         console.log('routeParams: ', $routeParams);
         // I need $routeParams.projectId to compose an API call. 
     });

     ...

 });

In the console, $routeParams is returned as an empty object. I know that if the Controller and route are defined in the app.config, the$routeParams are available, but the app.config already has definition for the given route which links to the PrimaryCtrl:

.config( function ($interpolateProvider, $routeProvider) {
   $routeProvider
    .when('/project/:projectId', {
        templateUrl : 'partials/_project_detail.html',
        controller: 'PrimaryCtrl',
        resolve: {
            project: function ($route, MyService) {
                return MyService.get('projects/', $route.current.params.projectId);
            },
        }
    })

So, how can I get access to the $routeParams in my SecondaryCtrl when $routeParams changes?

Upvotes: 0

Views: 1682

Answers (1)

Ye Liu
Ye Liu

Reputation: 8976

You can listen to the $routeChangeSuccess event inside of watching $routeParams, like this:

.controller('SecondaryCtrl', function ($scope, MyService) {

     $scope.$on('$routeChangeSuccess', function (event, current, previous) {
         // current is the current route
         // previous is the previous route
     });

     ...

 });

Angular Doc

Upvotes: 1

Related Questions