fauverism
fauverism

Reputation: 1992

What are the benefits of returning a function in templateURL?

From https://github.com/angular-ui/ui-router/wiki

templateUrl can also be a function that returns a url. It takes one preset parameter, stateParams, which is not injected.

$stateProvider.state('contacts', {
  templateUrl: function ($stateParams){
    return '/partials/contacts.' + $stateParams.filterBy + '.html';
  }
})

What would some of the benefits be of returning the function in the templateURL? Sorry if this is a bit vague. I'm trying to fully wrap my head around ui-router.

Upvotes: 0

Views: 170

Answers (2)

coma
coma

Reputation: 16649

The developers guide has a pretty good example for this in the directive section

The main idea is that you can "dynamically" choose the template that best fits the current instance:

angular.module('docsTemplateUrlDirective', [])
  .controller('Controller', ['$scope', function($scope) {
    $scope.customer = {
      name: 'Naomi',
      address: '1600 Amphitheatre'
    };
  }])
  .directive('myCustomer', function() {
    return {
      templateUrl: function(elem, attr){
        return 'customer-'+attr.type+'.html';
      }
    };
  });

As you may imagine, using this you are able of configuring the final template url by assigning an attribute called type in this case:

<div ng-controller="Controller">
  <div my-customer type="name"></div>
  <div my-customer type="address"></div>
</div>

On the ui-router scenario you can access to the state params instead, but the idea is the same.

Upvotes: 1

Michal Charemza
Michal Charemza

Reputation: 27012

A "benefit" is perhaps a strange way to put it. It adds a way for the router to dynamically decide what template to use for a given route, depending on $stateParams. An alternative way of achieving something similar would be to use ngIfs or ngSwitchs in the single template for a route.

Which one you use I think is probably up to your own preference / what you think a good coding practice is for the task in hand. If I have 2 radically different, and long, templates, I would probably use the function for a dynamic template url. If I had short, or very similar, templates, then I would probably use ngIf.

Also, I've used ui-router a few times now, and so far never used a function as templateUrl.

Upvotes: 1

Related Questions