How to use an URL param in a templateUrl using ngRoute?

Blake picture Blake · Apr 9, 2014 · Viewed 8.6k times · Source

I am building an angularjs app, my app.js looks like this. However, it throws Unknown provider: $routeParams error. Any idea why?

var angularSite = angular.module('angularSite', [
  'ui.router',
  'ngRoute',
  'siteController',
  'siteDirectives'
])
.config(['$routeProvider', '$routeParams',
  function($routeProvider,$routeParams) {
    $routeProvider.
      when('/Projects', {
        templateUrl: 'partials/projects.html',
        controller: 'ProjectController'
      }).
      when('/Projects/:projectId', {
        template: 'partials/pages/'+$routeParams.projectId+'.html',
        controller: 'ProjectDetailController'
      }).
      otherwise({
        redirectTo: '/About'
      });
  }]);

Answer

Mistalis picture Mistalis · Apr 7, 2017

$routeParams is a service and can not be injected in .config.

If you want to set your templateUrl from URL params, the correct way is to use a function to set the templateUrl (as following):

.when('/Projects/:projectId', {
    templateUrl: function(params) { // <-- 
        return 'partials/pages/' + params.projectId + '.html'    
    },
    controller: 'ProjectDetailController'
})