I'm struggling to understand Angular Directives and how they work. I have a simple array of objects in my controller, but creating the desired DOM structure from this data model is proving challenging. Any advice on best practices would be greatly appreciated.
Here is an example of my data model:
$scope.birthdays = [
{ name: "bob", dob:moment("09/20/1953"), cake: "vanilla"},
{ name: "michael", dob:moment("09/20/1953"), cake: "chocolate" },
{ name: "dave", dob:moment("09/20/1953"), cake: "chocolate" },
{ name: "chief", dob:moment("04/24/1977"), cake: "chocolate" },
{ name: "jerry", dob:moment("04/24/1977"), cake: "red velvet" },
{ name: "jerkface", dob:moment("04/24/1977"), cake: "i hate cake" },
{ name: "doug", dob:moment("05/10/1994"), cake: "marble" },
{ name: "jeff", dob:moment("05/10/1994"), cake: "vanilla" }
];
I aim to create a specific DOM structure based on this data, as shown below:
<h1>Birthday: 09/20/1953</h1>
<div class="birthday">
<h2>Name: bob</h2>
<h3>Cake: vanilla</h3>
</div>
<div class="birthday">
<h2>Name: michael</h2>
<h3>Cake: chocolate</h3>
</div>
<div class="birthday">
<h2>Name: dave</h2>
<h3>Cake: chocolate</h3>
</div>
<h1>Birthday: 04/24/1977</h1>
<div class="birthday">
<h2>Name: chief</h2>
<h3>Cake: chocolate</h3>
</div>
....
A similar structure can be seen in this plunker, although not exactly what I am aiming for.
The provided Plunker generates a different DOM structure than desired:
<div ng-repeat="birthday in birthdays" birthday-boy="">
<h3 ng-show="!birthdays[$index-1].dob.isSame(birthday.dob)" class="ng-binding" style="">
September 20th, 1953
</h3>
<div class="ng-binding">
Name: bob
</div>
<div class="ng-binding">
Cake: vanilla
</div>
</div>
...
My questions are:
- Is there a more efficient way to organize my data to achieve the desired DOM structure?
- If working with my existing data structure, do I need to modify the DOM outside of the ng-repeat directive?
- Could a custom wrapper around the ng-repeat directive be a solution? I am exploring the compile function but unsure.
Thank you for any assistance!