ad-hockery: /ad·hok'@r·ee/, n.
Gratuitous assumptions... which lead to the appearance of semi-intelligent behavior but are in fact entirely arbitrary. Jargon File

Dynamic templates in Angular routes

We’re building an application where content can be published using different layouts selected by an editor. In Angular this translates to a situation where the same route & controller will need to display content from the same $http endpoint using a range of different templates. The name of the template is included in the JSON data returned by the $http endpoint so it’s not known at the time the route is triggered.

Since Angular route definitions are static (at time of writing anyway – there is a proposal to allow templateUrl to be declared as a function) it wasn’t clear how we could do this. We experimented with responding to routeChanged events or implementing our own version of $routeProvider without finding a solution we were happy with.

I figured this wasn’t such an unusual requirement & went looking for an existing solution. I came across a very useful thread on Google Groups. The solution it suggests is simple; instead of a templateUrl the route uses a template containing an ng-include directive that uses a scope property for its path.

.when('/:articleSlug', {
    controller: 'ArticleCtrl',
    template: '<article ng-include="templateUrl"></article>'

In the controller we can simply assign $scope.templateUrl when the $http endpoint’s promise is resolved. Angular’s binding magic does the rest and the template is rendered.

This works really well. There are no additional HTTP requests, we’re not reinventing the wheel and it’s pretty clear what is going on.

Web Statistics