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

2

21

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!

Blindfish answered 17/12, 2013 at 15:24 Comment(0)
A
38

templateUrl can be a function accepting object of route parameters:

.when('/pages/:pageName', {
    templateUrl: function(params) {
        return 'views/pages/' + params.pageName + '.html';
    },
    controller: 'MainController'
});
Argumentative answered 17/12, 2013 at 15:38 Comment(1)
Thank you. this worked like a charm. Only one thing - missing a . between the ' and the html like so : + '.html' .Thank you again!Blindfish
T
5

templateUrl can be use as function with returning generated URL. We can manipulate url with passing argument which takes routeParams.

See the example.

.when('/:screenName/list',{
    templateUrl: function(params){
         return params.screenName +'/listUI'
    }
})

Hope this help.

Taciturnity answered 3/12, 2014 at 8:17 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.