Search code examples
angularjsangularjs-routing

Inject routes dynamically in angularjs


I'm using angular to dynamically create another angular app. I was wondering if there is a way to inject routes dynamically. Something like

angular.module('app').controller('CreateCtrl', function ($scope,$routeProvider) {
  var count = 0;

  $scope.addPage = function(){  
    $routeProvider.when('/'+count, {
       templateUrl: 'views/created.html',
       controller: 'CreatedCtrl'
     });
    count++;
  };

});

I know this code is silly but I hope it transmits what I'm trying to do. When user intercts with the application he/she will create new routes... is that possible?


Solution

  • There are two ways:

    Option 1

    modifying the routes object directly, as suggested in https://stackoverflow.com/a/13173667/17815

    $route.routes['/dynamic'] = {templateUrl: 'dynamic.tpl.html'};
    

    Be careful: you need to add both "/newurl" and "/newurl/" (with trailing slash). see the angular code:

    this.when = function(path, route) {
    routes[path] = extend({reloadOnSearch: true}, route);
    
    // create redirection for trailing slashes
    if (path) {
      var redirectPath = (path[path.length-1] == '/')
          ? path.substr(0, path.length-1)
          : path +'/';
    
      routes[redirectPath] = {redirectTo: path};
    }
    
    return this;
    };
    

    Option 2

    you can keep a reference to $routeProvider:

    var $routeProviderReference;
    var app = angular.module('myApp', ['myApp.controllers']);
    
    app.config(['$routeProvider', function($routeProvider) {
        $routeProviderReference = $routeProvider;
    }]);
    

    See http://blog.brunoscopelliti.com/how-to-defer-route-definition-in-an-angularjs-web-app

    This is polluting the global namespace but you still use the interface to mutate the routes object. I guess this makes it easier to maintain. Maybe you can try to put it in a closure.

    In any case, keep in mind that you are expected to do it in a provider to make the application robust. "define before use".