1

I need to create I dynamic ng-repeat, after populate it I want to add a click function on each repeat item and then on click I want to add another repeat inside the clicked element. This for create a little filme manager, so on folder click I want to add a list of file(

<li class="item_grid" ng-repeat="(id,f) in files | filter:query"  id="{{f.id}}" file-directive-right>
<div class="title" ng-click="clicked(id)">{{f.id}} - {{f.titolo}}</div>
</li>

this is my code the problem is add a repeat onclick, which is the best way?

2
  • You already have an ng-click inside the repeat? Commented Jan 21, 2015 at 20:15
  • yes, the problem is only insert another repeat on click Commented Jan 21, 2015 at 20:33

1 Answer 1

2

It's probably best to design this with a directive and add DOM elements dynamically, but you could also do this with just "recursive" ng-include - I'll let others comment on whether this is a best practice or an anti-pattern :)

Basically, this leverages the child scope that ng-repeat creates for each child and ng-init to re-alias the name of the list (of folders, for example):

Let's say, the basic structure of folder contents is like so:

<ul>
  contents of: {{folder.name}}
  <li ng-repeat="f in folder.contents">

    <span ng-click="getFolderContents(f)">{{f.name}}</span>

    <ul ng-if="f.contents.length">
       contents of: {{f.name}}
       <li ng-repeat="childF in f.contents">
         ... etc
       </li>
    </ul>
  </li>
</ul>

You can see the recursive nature. So, if we could abstract the inner folder into an ng-include, then we could reuse it.

The final solution would look like so:

<div ng-controller="folderCtrl">

    <ul ng-include="'folderTemplate'"></ul>


    <script type="text/ng-template" id="folderTemplate">
       contents of: {{folder.name}}
       <li ng-repeat="f in folder.contents" ng-init="folder = f">

          <span ng-click="getFolderContents(f)">{{f.name}}</span>

          <ul ng-include="'folderTemplate'" ng-if="f.contents.length"></ul>
       </li>

    </script>  
</div>

Notice the ng-init="folder = f". It sets the alias variable folder for each child scope. It is also, not incidentally, the same variable used by its parent, and ultimately, the root:

$scope.folder = {name: "folder 1", contents: []};

getFolderContents is just a function that populates folder.contents for a clicked-on folder.

Here's a plunker to play with

Sign up to request clarification or add additional context in comments.

1 Comment

thank u very much! I play a bit with this code and I solve the problem!

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.