AngularJS - use routeProvider "when" variables to construct templateUrl name?

Georgi Angelov picture Georgi Angelov · Dec 17, 2013 · Viewed 22.6k times · Source

So this is what I am trying to accomplish:

'use strict';

var app = angular.module('myModule', ['ngRoute']);

app.config(function($routeProvider) {
  $routeProvider
    .when('/', {
      redirectTo: '/pages'
    })
    .when('/pages/:pageName', {
      templateUrl: 'views/pages/'+pageName+'html',
      controller: 'MainController'
    });
});

Basically, I want to use the uri to determine which template is used. Currently I get an error that pageName is not defined which I understand. What would be a different way of doing this? Thanks!

Answer

dfsq picture dfsq · Dec 17, 2013

templateUrl can be a function accepting object of route parameters:

.when('/pages/:pageName', {
    templateUrl: function(params) {
        return 'views/pages/' + params.pageName + '.html';
    },
    controller: 'MainController'
});