Wednesday, June 5, 2024
 Popular · Latest · Hot · Upcoming
70
rated 0 times [  72] [ 2]  / answers: 1 / hits: 18281  / 11 Years ago, wed, september 25, 2013, 12:00:00

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?


More From » angularjs

 Answers
3

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.


[#75426] Wednesday, September 25, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
collinarnoldp

Total Points: 10
Total Questions: 122
Total Answers: 109

Location: Spain
Member since Thu, Dec 23, 2021
3 Years ago
collinarnoldp questions
;