单击列表项后显示子列表

时间:2016-10-04 18:24:39

标签: javascript angularjs json

我将以下json发送给我的观点:

$scope.mockData = [
  {
    "folder": "folder1",
    "reports": [{ "name": "report1" }, { "name": "report2" }, { "name": "report3" }]
  },
  {
    "folder": "folder2",
    "reports": [{ "name": "report5" }, { "name": "report6" }, { "name": "report7" }]
  },
  {
    "folder": "folder3",
    "reports": [{ "name": "report8" }, { "name": "report9" }, { "name": "report10" }]
  }
];

要迭代文件夹列表,我在我的视图中有这个:

<div class="row" ng-repeat="item in mockData | filter:query">
  <div class="col-md-6">
    <a href="" class="list-group-item" ng-cloak >
      <i class="glyphicon glyphicon-folder-close"></i>
      &nbsp;{{item.folder}}
    </a>
  </div>
</div>

我想在我的视图中实现以下功能: 当我点击:

<a href="" class="list-group-item" ng-cloak >
      <i class="glyphicon glyphicon-folder-close"></i>
      &nbsp;{{item.folder}}
</a> 

我应该会看到一个新的div,但现在显示的是:

"reports": [{ "name": "report1" }, { "name": "report2" }, { "name": "report3" }

我该怎么做?

1 个答案:

答案 0 :(得分:1)

您可以在MOCK JSON中添加一个布尔参数,例如'showFolderContents':false。将ng-click行为添加到文件夹图标,单击它时,将该参数切换为true / false。然后在你的ng-repeat ='mockData'项目中,你必须使用ng-show ='item.showFolderContents'在item.reports'中创建一个嵌套的ng-repeat ='报告。

您可以使用以下内容处理ng-click行为:

<i class="glyphicon glyphicon-folder-close" ng-click='toggleShowingFolderContents(item)></i>

并在你的角度中产生如下函数:

$scope.toggleShowingFolderContents = function(item){
item.showFolderContents = !item.showFolderContents
}

所以你的HTML会像这样:

<div class="row" ng-repeat="item in mockData | filter:query">
<div class="col-md-6">
<a href="" class="list-group-item" ng-cloak >
  <i class="glyphicon glyphicon-folder-close" ng-  click='toggleShowingFolderContents(item)></i>
<div ng-show='item.showFolderContents'>
<div ng-repeat='report in item.reports'>
{{report.name}}
</div>
</div>