0

I have 2 directives, one that displays a list of objects, and other one that adds objects to that list. The problem that I have is that the list are tied to another elements list this way:

Main code:

<!--main code -->
<div>
    <ul>
        <li>
            <element-a></element-a>
        </li>
        <li>
            <element-a></element-a>
        </li>
        <li>
            <element-a></element-a>
        </li>
        <li>
            <element-a></element-a>
        </li>
    </ul>
</div>

Element A template

<!-- element-a template -->
<ul>
    <li> 
        <my-element-list></my-element-list>
    </li>
    <li>
        <my-element-list></my-element-list>
    </li>
    <li>
        <my-element-list></my-element-list>
    </li>
    <li>
        <my-element-list></my-element-list>
    </li>
</ul>

My List Template:

<!-- my-element-list template -->
<button type="button" data-ng-click="addElement()">Add</button>
<ul>
    <li>
        my element data
    </li>
    <li>
        my element data
    </li>
    <li>
        my element data
    </li>
</ul>

I'm new to angular, but I don't want to have the add directive on each list, as that would have a lot of not needed code added to the html. Also the add is a directive that has a template, etc, that is suppossed to show a modal dialog which will request the element data.

Is this the correct approach for doing this? How can I get the add modal dialog displayed when the add button is clicked? I tried with $broadcast and $emit, but the add directive is not a parent/child of the element list.

Allan Kimmer Jensen
  • 4,333
  • 2
  • 31
  • 53
Mg.
  • 1,469
  • 2
  • 16
  • 29

2 Answers2

1

You might want to try and go about this a different way. Your list should be generated from an array of items in your controller, and then rendered into the template using the built-in Angular directive ng-repeat. Then, adding new items to the list should be as simple as making sure the addElement() function in your controller is adding items to the array. If each element in your list also needs it's own template, look into using the ng-include directive within the ng-repeat loop.

ng-repeat docs

ng-include docs

Hacknightly
  • 5,109
  • 1
  • 26
  • 27
  • That's not the problem. The items are rendered that way. Just showing the data structure to show why $emit and $broadcast does not work. – Mg. Feb 10 '14 at 15:11