Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does AngularJS have dynamic routing?

Does angular support dynamic routing at all? Maybe some trick like this:

$routeProvider.when('/:ctrl/:action', 
                     getRoute($routeParams.ctrl,$routeParams.action))

function getRoute(ctrl, action){
   return {
      templateUrl: ctrl+"-"+action+".html"
      controller: 'myCtrl'
   }
}

Please help me, I need to get templateUrl based out of routeParams

like image 291
iLemming Avatar asked Dec 26 '22 01:12

iLemming


1 Answers

This is a late answer but I came across this problem myself, but it turns out that the solution by Dan conflicts with ngAnimate classes on the ngView directive, and the view is shown but the ng-leave animation will immediately be applied and hide the view opened with his dynamic routing.

I found the perfect solution here, and it's available in 1.1.5 +

In the $routeProvider, the templateUrl value can be a function, and is passed the route parameters:

app.config(function ($routeProvider) {
$routeProvider
    .when('/:page', {
         templateUrl: function(routeParams){
             return '/partials/'+routeParams.page+'.html';
        }
    })
});

Though the controller can't be given as a function so my solution is to give it in the template html as per usual with ng-controller="HomeCtrl".

Using this solution we can route by convention in Angular. I hope this helps others who weren't keen on manually adding every route to the routeProvider.

like image 169
caffeinated.tech Avatar answered Jan 22 '23 13:01

caffeinated.tech