Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS directive with multiple templates

Tags:

Task:

  • To show contact.
  • Contact is JSON data, let's say {name: "Mark", location: "England", phones: [...]}.
  • Contact could be shown in multiple ways: compact / detailed / enhanced with additional info (shared contacts - additional directive)

Because contact could be shown on different pages in different places it's naturally to create directive (widget) for contact, but here is question: "How to organize same widget with multiple templates?"

Options:

  1. Create one directive with one template, that hides sections according to contact "type" - big template with possibly a lot of ng-switch and ng-if
  2. Create directive for each template - almost same directives with only different template (or templateURL)
  3. To load templates dynamically while linking - has problems with transclusion and replacing (merging attributes)

Whats your expirience with solving these problem?

like image 886
Stanislav Yermakov Avatar asked Sep 25 '13 21:09

Stanislav Yermakov


1 Answers

Personally I think that Option 2 offers a clean separation between display modes. I have created a working CodePen example to illustrate how you might accomplish this cleanly by using separate directives for each template.

The method I used in my CodePen example utilizes a template factory which is injected into each directive via Angular DI. The template factory implementation is very clean since it merely uses ng-include template strings for each of the different supported display modes (compact & detailed). The actual HTML templates (partials) can be housed in external view files or internal script blocks.

Using the contact directives are easy:

<contact compact ng-repeat="contact in contacts" ng-model="contact"></contact> 

This creates a compact version of the contact list.

<contact detailed ng-repeat="contact in contacts" ng-model="contact"></contact> 

This creates a detailed contact listing.

I will admit that I haven't deployed code like this to production so there may be scalability or other concerns I haven't considered. I hope the code I provided answers your questions or at least provides inspiration for further exploration.

like image 195
Adam Avatar answered Oct 19 '22 07:10

Adam