Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS - how to have a directive with a dynamic sub-directive

Tags:

angularjs

Really struggling with this - have tried every way I can think of. Hopefully, somebody can help.

I have a directive which creates the outline of a custom control for me. The central part of the custom control is to be represented by a further dynamically-generated directive based on the value of a scope variable on the outer directive. The scope variable contains the name of the inner directive. I am doing this because my page will have multiple dynamically-generated elements all with a common layout but different inner content.

i.e. an example of my outer directive:

<div data-inner="{{inner}}">
    <!-- div content here --->
<div {{inner}} />

{{inner}} is set to the name of a further directive - in this case search. My page should therefore become:

<div data-inner="search">
    <!-- div content here --->
<div search />

with search on the lower div also being replaced by the content of that directive.

Any ideas?

UPDATE Here's a basic jsFiddle representing the issue I have - note the third div is not displayed.

like image 646
jwest Avatar asked Feb 01 '13 09:02

jwest


2 Answers

I have create a fiddle here.

These are the directives.

<script type="text/ng-template" id="one">
    <div class="one"></div>
</script>
<script type="text/ng-template" id="two">
     <div class="two"></div>
</script>

And here you do dynamic loading

<div ng-repeat='template in inner' ng-include='template'></div>

See if this helps you, and solves your purpose. I am making each directive into a template and then using ng include

like image 102
Chandermani Avatar answered Nov 05 '22 07:11

Chandermani


Try this fiddle http://jsfiddle.net/xpKwb/12/

You can use ngSwitch

<div ng-repeat='template in inner'>
    <div ng-switch on="template">
        <div ng-switch-when="one">
            <div class='one'></div>
        </div>
        <div ng-switch-when="two">
            <div class='two'></div>

        </div>
    </div>
like image 37
ankush Avatar answered Nov 05 '22 09:11

ankush