Taras Kovalenko
Taras Kovalenko

Reputation: 2393

AngularJs create templates directive

I would like create directive with more templates. And selected template depends on some value (like template-type). Then if I invoke my directive in html page, and change type template-type, need changed html template. Like this:

<template-factory template-type={{foo}}></template-factory>

I think what I can created one html template that contains all my templates, and select from ng-if help. But I think what it is not very well. Help me please, select best solutions for this task.

Upvotes: 1

Views: 975

Answers (1)

Joey Ciechanowicz
Joey Ciechanowicz

Reputation: 3663

Interestingly in a directive you can pass a function as your template which can then return a string which is used for the template.

Take a look at What are the benefits of a directive template function in Angularjs? to see how this is done and the pros/cons.

From the angular docs:

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';
    }
  };
});

Upvotes: 2

Related Questions