Cesar Rodriguez Cesar Rodriguez - 3 months ago 14
AngularJS Question

It's possible to change the templateURL through attributes in a angularjs directive?

I have the following directive:

(function() {

'use strict';
function header() {
return {
templateUrl: '/app/home/homeheader.html'
};
}
angular.module('app').directive('appheader', header);
})();


Due to I need to change the header depending of the page what used it, I guess if I can do in the DOM something like this:

index.html

<appheader page="index"></appheader>


signUp.html

<appheader page="signUp"></appheader>


...

Then in the directive, assign the template that I want.

I've reading some on the web but I did not found any solution. There are so

Answer

You can pass a function into templateUrl, check the page attribute and let your imagination go wild!

Take a look at the Creating Custom Directives documentation.

Heres an example to get you started:

(function() {

  'use strict';

  function header() {
    return {
      templateUrl: function(elem, attrs) {

        // check the attribute value
        if (attrs.page === "home") {
          return '/app/home/homeheader.html';
        } else {
          return '/app/home/signupheader.html';
        }

        // OR use the attribute value as part of the template
        return '/app/home/' + attrs.page + 'header.html';

      }
    };
  }

  angular.module('app').directive('appheader', header);

})();