How to use an URL param in a templateUrl using ngRoute? [duplicate]
Asked Answered
L

3

9

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'
      });
  }]);
Leroi answered 9/4, 2014 at 20:37 Comment(2)
$routeParams is a service and not a provider, what are you trying to accomplish with it in your config method? documentation: docs.angularjs.org/api/ngRoute/service/$routeParams#!Residue
I've found this link and I believe it answers your question.Mickelson
W
0

$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'
})
Wretch answered 7/4, 2017 at 8:14 Comment(0)
G
-1

Available in AngularJS 1.2 access route params at a configuration level replace.

template: 'partials/pages/'+$routeParams.projectId+'.html',

with:

templateUrl: function(params){ return 'partials/pages/' + params.projectId + 'html'; }

source - AngularJS - How to use $routeParams in generating the templateUrl?

Grith answered 17/7, 2015 at 18:22 Comment(0)
F
-1

In the config of an Angular module is not allowed to use services. $routeParams is a Service so you can not use it there.

I would recommend you to include one template or another through your controller ProjectDetailController. In this controller you can inject and use the service $routeParams, in order to choose one template or another. Something like:

So, your config:

 when('/Projects/:projectId', {
    template: 'partials/pages/main.html',
    controller: 'ProjectDetailController'
  }).

Your controller:

Controller.$inject = ['$routeParams'];

/* @ngInject */
function Controller($routeParams) {
  var vm = this;
  vm.template = 'partials/pages/'+$routeParams.projectId+'.html';
}

And your main.html template:

<ng-include src="vm.template"/>
Fugue answered 30/11, 2016 at 13:53 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.