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?
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.
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) .
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With