我是 AngularJS 的新手,遇到了一个问题。
需要创建消息历史树,它在父项上提供展开/折叠功能。
我已经创建了 View :
<div class="tree">
<ul>
<li ng-repeat="appt in apptsToFilter() | filter: groupByAppt" ng-click="showChilds()">
<span>{{appt.startTime}} - Appt. Id: {{appt.appointmentId}} </span>
<ul>
<li ng-repeat="item in appts | filter: {appointmentId: appt.appointmentId}" ng-show="active">
<span>{{item.message}}</span>
</li>
</ul>
</li>
</ul>
</div>
这是我的 View Controller :
function MessageHistoryController($scope, $routeParams, MessageHistoryResource) {
......//some code
$scope.active = false;
$scope.showChilds = function() {
if ($scope.active == false) {
$scope.active = true;
} else {
$scope.active = false;
}
};
}
当我展开第一个父项时,这是我得到的:
ParentItem2:
- Child1
- Child2
- Child3
ParentItem2
- Child1
- Child2
ParentItem3
- Child1
当我点击任何父项时 - 所有 我的子树展开或折叠。
但我预料到了这个结果,如下所示(只应展开点击的项目):
ParentItem2:
- Child1
- Child2
- Child3
ParentItem2
ParentItem3
任何想法都会受到赞赏。谢谢。
最佳答案
那是因为您将所有父项、可点击项都设置为一个 bool 值。这可以在没有 active
bool 的 HTML 中解决。
将您的显示/隐藏元素设置为:
ng-show="appt.active"
然后将您的点击调用设置为:
ng-click="appt.active = !appt.active"
完整示例:
<div class="tree">
<ul>
<li ng-repeat="appt in apptsToFilter() | filter: groupByAppt" ng-click="appt.active = !appt.active">
<span>{{appt.startTime}} - Appt. Id: {{appt.appointmentId}} </span>
<ul>
<li ng-repeat="item in appts | filter: {appointmentId: appt.appointmentId}" ng-show="appt.active">
<span>{{item.message}}</span>
</li>
</ul>
</li>
</ul>
</div>
即使 appt.active
在单击时会初始化为 undefined,但它会变为 true,至少在我这边是这样,这就是我处理这些情况的方式。
您还可以遍历 appt
并在 javascript 中定义 active。
为了将来引用,您可以将 $scope.showChilds
函数简化为:
$scope.showChilds = function () {
$scope.active = !$scope.active
}
关于javascript - 展开/折叠树中的子元素(AngularJS),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20384702/