W3docs

How to Dynamically Change Template URL in Angular JS Directives

TemplateUrl can be not only a value. It can be a function with any arguments, which returns a value as URL. See how it looks.

AngularJS directives are a core component of the framework. Today, we will cover how to dynamically set the AngularJS directive templateUrl.

Warning

Since AngularJS is now a deprecated framework, you can use modern JavaScript frameworks like Vuejs, React and Angular, instead. This guide applies only to legacy AngularJS 1.x maintenance projects.

We all know there is template and templateUrl. You may have used them frequently, but there is a less common syntax: templateUrl can be a function instead of a static string. This function receives arguments and returns the URL string. Let's see how it looks.

example

module.directive("myDirective", function() {
  return {     
    // ...
    templateUrl: function(elem, attrs) {
        // elem: the current DOM element
        // attrs: an object of normalized attributes
        if (attrs.dynamicTemplate === 'advanced') {
            return 'views/advanced-template.html';
        }
        return 'views/default-template.html';
    },
    link: function(scope, el, attrs) {
        // linking logic
    }
  }
})

The templateUrl function receives the current element (elem) and its attributes (attrs). You can use these parameters to conditionally return different template paths based on component configuration or state.