ajmajmajma
ajmajmajma

Reputation: 14216

Angular, ng-repeat with some kind of recursive search

I have a bit of a strange problem I am trying to solve. I have an idea of how I may be able to solve it, but I'm certainly open to any advice or other directions I could take because I'm not entirely sure this is the right route.

What I'm trying to do is have an ng-repeat but have it show the lowest level items in the object (it's a big object) that are inside a key of 'apps'.

So the object is set up like so ( I would like to note it would be great if I didn't have to change this object too much as it is being used elsewhere as well) Here is one item inside the object.

$scope.myObject = [{
        name: 'Name1', 
        subs: [
            {
                name: 'Sub 1', 
                subs: [
                        {
                            name: 'Sub 1-1', 
                            apps: [
                                {
                                name: 'App 1' 
                                }
                            ]
                        }
                ],
                apps: [
                        {
                            name: 'App'
                        }
                ]
            }

So the idea is - any level inside the object can either have subs or apps. Subs means it has group inside of it, and the apps array is the lowest desired level. My intended effect is do be able to do a repeat of myObject where it only shows the apps, the order does not really matter right now but I would like to traverse inside the whole object and pull out any apps, regardless of how deep they are.

I could use some guidance in how to retrieve all the apps inside this object, any help would be greatly appreciated. Thanks!

Edit 1 :

So to clarify, the end result I am looking for is to do something like an ng-repeat (again it doesn't have to be a repeat necessarily ) and end up with a list of all the apps, regardless of where they are in the object.

so like -

  <div ng-repeat="items in myObject" >
   {{name}}
  </div> 

would spit back only apps , so App 1 and App in this example object.

Edit 2 : Here is my recursion attempt

   <div ng-repeat="item in myObject">
   <div ng-repeat="subs in item.subs" ng-include="'subTracks.html'" >

   <script type="text/ng-template" id="subTracks.html">
     <div ng-repeat="app in subs.apps">
    {{app.name}}
    </div>
    <div ng-repeat="subs in subs.subs" ng-include="'subTracks.html'" >

    </div>
</script>

Upvotes: 3

Views: 122

Answers (1)

Code Whisperer
Code Whisperer

Reputation: 23662

You will want to convert the nested array into a flat array before doing a repeat on it.

You can use a custom reduce function, or check out this article http://bost.ocks.org/mike/nest/

Which is about d3.nest which can generate the array you need.

Upvotes: 2

Related Questions