Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Our application has 2-level navigating. We want to use AngularJS $routeProvider to dynamically provide templates to an <ng-view />. I was thinking of doing something along the lines of this:

angular.module('myApp', []). config(['$routeProvider', function($routeProvider) {     $routeProvider.when('/:primaryNav/:secondaryNav', {         templateUrl: 'resources/angular/templates/nav/'+<<primaryNavHere>>+'/'+<<secondaryNavHere>>+'.html'     }); }]); 

I just don't know how to populate the parts within the <<>>. I know the primaryNav and secondaryNav get bound to the $routeParams, but how do I access $routeParams here in order to dynamically serve up the template?

like image 300
dnc253 Avatar asked Jul 18 '12 05:07

dnc253


People also ask

How to use route params in AngularJS?

The $routeParams service allows you to retrieve the current set of route parameters. Requires the ngRoute module to be installed. The route parameters are a combination of $location 's search() and path() . The path parameters are extracted when the $route path is matched.

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 templateUrl in AngularJS?

templateUrl can also be a function which returns the URL of an HTML template to be loaded and used for the directive. AngularJS will call the templateUrl function with two parameters: the element that the directive was called on, and an attr object associated with that element.


1 Answers

This very helpful feature is now available starting at version 1.1.2 of AngularJS. It's considered unstable but I have used it (1.1.3) and it works fine.

Basically you can use a function to generate a templateUrl string. The function is passed the route parameters that you can use to build and return the templateUrl string.

var app = angular.module('app',[]);  app.config(     function($routeProvider) {         $routeProvider.             when('/', {templateUrl:'/home'}).             when('/users/:user_id',                  {                        controller:UserView,                      templateUrl: function(params){ return '/users/view/' + params.user_id; }                 }             ).             otherwise({redirectTo:'/'});     } ); 

Many thanks to https://github.com/lrlopez for the pull request.

https://github.com/angular/angular.js/pull/1524

like image 147
jlareau Avatar answered Oct 22 '22 12:10

jlareau