Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
544 views
in Technique[技术] by (71.8m points)

javascript - Looping through deep objects in ng-repeat

I'm in angular and i have a object like this.

var items = [{
    title: 'Something',
    children: [
        { title: 'Hello World' },
        { title: 'Hello Overflow' },
        { title: 'John Doe', children: [
            { title: 'Amazing title' },
            { title: 'Google it' },
            { title: 'I'm a child', children: [
                { title: 'Another ' },
                { title: 'He's my brother' },
                { title: 'She's my mother.', children: [
                    {title: 'You never know if I'm going to have children'}
                ]}
            ]}
        ]}
    ]
}];

I wan't to loop through all of these so i have something like this.

????? Something

?????? ? Hello World

?????? ? Hello Overflow

?????? ? John Doe

??????????? Amazing Title

??????????? Google it

??????????? I'm a child

??????????????? Another

??????????????? He's my brother

??????????????? She's my mother

??????????????????? You never know if I'm going to have children

The problem is I wouldn't know how deep this object will go or what's in it. so I wouldn't be able to do it manually. I have done a basic loop with ng-repeat in the fiddle provided at the bottom, but i can't figure out how I can automatically loop through these and create nested <ul>'s and <li>'s.

What would be the best way to accomplish this?

Demo: http://jsfiddle.net/XtgLM/

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You don't need to make a custom directive, what you want is to use an inline template that calls it's self.

I forked your fiddle.

http://jsfiddle.net/MasterMorality/E99Gh/2/

basically it looks like this:

<script type='text/ng-template' id="item.html">
    ...
    <div ng-repeat="x in x.childrens" ng-include="'item.html'"></div>
</script>
...
<div ng-repeat="x in things" ng-include="'item.html'"></div>

I should note that you are not actually overwriting x, since angular creates a new scope for each repeated item.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...