Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS - on button click nest div templates

I am working on a module where I will have div elements that are nested within div elements that may also be nested in div elements. These div elements will be created by the user when they click a button. The divs may end up looking like so:

  1. div1

    1.1. div2

    1.2. div3

    1.3. div4

       1.3.1 div5
    
       1.3.2 div6
    

2.div7

3.div8

and so forth...

Each of these divs will simply be an html template and I want to bind the data for each of these divs, say the div has a title, and so I will bind each div.

My first plan of action was to use ng-include and simply create ng-includes dynamically by the user and that way the templates will by loaded by ng-include. However, as I have found out, nested ng-includes are not possible due to dependancy issues.

I am aware of libraries that are cooked by users that try to hack their way around doing nesting of ng-includes but I am looking for a good practice of nesting templates, while staying away from extra libraries.

Any suggestions on what would be the best way to dynamically nest templates?

like image 278
Georgi Angelov Avatar asked Jun 30 '13 16:06

Georgi Angelov


1 Answers

What I understand is you want to use a template with ng-include in a recursive way (Hope I understand well your needs)

I made you a jsfiddle to show you how I'm doing it : http://jsfiddle.net/Mm32t/3/

Below, the jsfiddle code :

JS :

function myCtrl($scope)
{
    $scope.data = [
        {
            title: "N°1 - first level",
            nodes: [
                {
                    title: "N°1 - second level",
                },
                {
                    title: "N°2 - second level",
                    nodes: [
                        {
                            title: "N°1 - third level",
                        },
                        {
                            title: "N°2 - third level",
                        },
                    ],
                },
            ],
         },
         {
            title: "N°2 - first level",
         },
    ];
}

HTML :

<script type="text/ng-template" id="common_template">
    <ul>
        <li data-ng-repeat="node in nodes">
            <h6>{{node.title}}</h6>
            <div data-ng-show="node.nodes" data-ng-include="'common_template'" data-ng-init="nodes = node.nodes"></div><!-- The best here is to use data-ui-if insted of data-ng-show but it require angular-ui-->
        </li>
    </ul>
</script>

<div data-ng-controller="myCtrl" data-ng-include="'common_template'" data-ng-init="nodes = data"></div>

like image 154
Gabriel Avatar answered Oct 28 '22 08:10

Gabriel