AngularJS nested ng-repeat onclick

2019-05-30 05:30发布

问题:

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?

回答1:

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