0

I have a custom directive named hero And I want to create a nested view for multiple heros. Demo

I want to get a view like this:

<hero a="1">
    <hero a="2">
        <hero a="3">
            <hero a="4"></hero>
        </hero>
    </hero>
</hero>

and controller is like this:

var myApp = angular.module('myApp',[]);

function MyCtrl($scope) {
    var elements = [
        angular.element('<hero a="1"></hero>'), 
        angular.element('<hero a="2"></hero>'), 
        angular.element('<hero a="3"></hero>'),
        angular.element('<hero a="4"></hero>')
    ];

    var content;

    for(var i = 0; i < elements.length; i++){

        if(!content){
                content = elements[i];
        }else{
                content.append(elements[i]);            
        }
    }

    console.log(content[0]);        
}

but it appears :

<hero a="1">
    <hero a="2"></hero>
    <hero a="3"></hero>
    <hero a="4"></hero>
</hero>
2
  • You missed an content = elements[i] after content.append(..) Commented Feb 23, 2017 at 18:07
  • I updated demo but did not work Commented Feb 23, 2017 at 19:31

1 Answer 1

1

EDIT: Full refactor of the idea exposed on the original answer.

You just need to keep "indexed" your last node so you can access to it and append the new (current) element to it. I show the relevant part of the code below.

function MyCtrl($scope) {
    //... your code omitted for brevity

   var content;
   var eArr = [];

    for(var i = 0; i < elements.length; i++){

        if(!content){
                content = elements[i];
        }else{
                elements[i - 1].append(elements[i]);
        }
        eArr.push(elements[i]);
    }

    console.log(content[0]);
}
Sign up to request clarification or add additional context in comments.

4 Comments

Please, see my answer edited. With an ief should work.
OK, let me check the demo. This seemed to be not so complicated. I'll give you feedback later
@bookmarker, I just edited my answer. See the new result gotten with this code. Sorry for the wrong previous answer. I tested this one and I got the result you said you needed.
Thanks for solution

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.