Search code examples
javascriptangularjsurl-routingsingle-page-applicationangularjs-routing

Defining a controller with $routeProvider using a function


I'm trying the following code, but with no success:

MyApp.config(['$routeProvider', '$provide', function($routeProvider, $provide) {
$routeProvider
    .when('/', {
        redirectTo: '/'
    })


    .when('/:page', {
        templateUrl: function($routeParams) {
            return 'views/'+ $routeParams.page +'.html';
        },

    })
    .when('/:page/:child*', {
        templateUrl: function($routeParams) {
            return 'views/'+ $routeParams.page + '/' + $routeParams.child + '.html';
        },
        controller: function($routeParams) {
            return  $routeParams.child + '.' +  $routeParams.page + 'Controller';
         },
    })

    .otherwise({
        redirectTo: '/'
    });
}]);

what i want to accomplish is to define the controller for each view with a function based on the $routParams variable:

controller: function($routeParams) {
            return  $routeParams.child + '.' +  $routeParams.page + 'Controller';
         },

while it works pretty good with the templateUrl, it doesn't seem to work when i define the controller.


Solution

  • The idea for achieving this would be, create a constant variable that would be assigned to controller inside that we want to load conditionally, we want set controller name by watching $routeParams, for that we could watch for $routeChangeStart and accordingly we will set costants.controllerName value, which would be the name of controller.

    You could achieve this by something doing like below.

    Constant

    MyApp.constant('constants',{
      controllerName : ''
    });
    

    Config

    MyApp.config(['$routeProvider', '$provide','constants', function($routeProvider, $provide, constants) {
        $routeProvider
        .when('/', {
          redirectTo: '/'
        })
        .when('/:page', {
          templateUrl: function($routeParams) {
            return 'views/' + $routeParams.page + '.html';
          }
        })
        .when('/:page/:child*', {
          templateUrl: function($routeParams) {
            return 'views/' + $routeParams.page + '/' + $routeParams.child + '.html';
          },
          controller: constants.controllerName
        })
        .otherwise({
          redirectTo: '/'
        });
    }]);
    

    Run Block

    MyApp.run(['$rootScope', '$location', 'constants', '$routeParams',
      function($rootScope, $location, constants, $routeParams) {
        // register listener to watch route changes
        $rootScope.$on("$routeChangeStart", function(event, next, current) {
            constants.controllerName = $routeParams.child + '.' + $routeParams.page + 'Controller'; //set controller name on $routeChangeStart
        });
    }]);
    

    I haven't tried this, I believe this code should work, Thanks.