Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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!

like image 232
Georgi Angelov Avatar asked Dec 17 '13 15:12

Georgi Angelov


People also ask

How do I get templateUrl in Angularjs?

templateUrl returned a function instead of a string. To get it to work, all I had to do was pass back in $stateParams like so: $state. current. templateUrl($stateParams) .

What is routeProvider in Angularjs?

Routing allows us to create Single Page Applications. To do this, we use ng-view and ng-template directives, and $routeProvider services. We use $routeProvider to configure the routes. The config() takes a function that takes the $routeProvider as a parameter and the routing configuration goes inside the function.


1 Answers

templateUrl can be a function accepting object of route parameters:

.when('/pages/:pageName', {     templateUrl: function(params) {         return 'views/pages/' + params.pageName + '.html';     },     controller: 'MainController' }); 
like image 107
dfsq Avatar answered Oct 11 '22 04:10

dfsq