显示和隐藏一个<div>在ng-repeat内与'dir分页'(AngularJS)



在这个网站上,我已经多次看到这个问题,但都不适合我,因为有两件事:我需要div在单击"选项"按钮时切换,但在单击div外部时隐藏;我需要它来处理dirPagination。

我看到了这个答案,它运行良好,但有一个问题我无法解决:它同时显示所有隐藏的div,而不是只显示我单击的div

这是我的代码:

<body ng-controller="MainCtrl">
<!-- pagination -->
<dir-pagination-controls
max-size="7"
direction-links="true"
boundary-links="true">
</dir-pagination-controls>
<ul>
<li dir-paginate="report in reports | itemsPerPage:4">
<a href="#" ng-click="showOptions($event)">Options</a>
<h3>{{report.Title}}</h3>
<div class="options" ng-show="dp">
<p>These are some options</p>
</div>
</li>
</ul>
</body>

和JS显示选项:

//options div
$scope.showOptions = function(event){
if($scope.dp === false || $scope.dp === undefined) {
$scope.dp = true;
event.stopPropagation();
} else {
$scope.dp = false;
}
};
window.onclick = function(){
if($scope.dp){
$scope.dp = false;
$scope.$apply();
}
};

我做了一个Plunker,以防你想在行动中使用:我的Plunker链接
有人能帮我解决这个问题吗?:(

在报表数组中添加一个新的布尔属性,例如show

var reports = [
{
"ID":1,
"Title":"Report 1",
"Show":false
},
{
"ID":2,
"Title":"Report 2",
"Show":false
}
]

将中的属性应用于ng-show,并将当前report范围对象传递到showOptions方法,以编写隐藏和显示的逻辑。

<li dir-paginate="report in reports | itemsPerPage:4">
<a href="#" ng-click="showOptions($event,report)">Options</a>
<h3>{{report.Title}}</h3>
<div class="options" ng-show="report.Show">
<p>These are some options</p>
</div>
</li>

$scope.showOptions = function(event,report){
report.Show=!report.Show;
/*you can iterate through each reports and change show to false if the clicked report id not equal to report id , Angular JS will automatically update the scope in to the view*/
reports.forEach(function(item, index) {
if (item.ID !== report.ID) {
item.Show = false;
}
});
if($scope.dp === false || $scope.dp === undefined) {
$scope.dp = true;
event.stopPropagation();
} else {
$scope.dp = false;
}
};

https://next.plnkr.co/edit/hnhWMrgR3GMtVcES

您需要为要显示的每个div使用一个单独的变量。您可以将dp属性添加到报告中。不需要循环查看报告来隐藏它们。您只需跟踪当前可见的报告,并在切换另一个报告时将其隐藏即可。

以下是相关的HTML:

<li dir-paginate="report in reports | itemsPerPage:4">
<a href="#" ng-click="showOptions($event, report)">Options</a>
<h3>{{report.Title}}</h3>
<div class="options" ng-show="report.dp">
<p>These are some options</p>
</div>
</li>

和JavaScript

var visibleReport;
$scope.showOptions = function(event, report){
if (report == visibleReport) {
report.dp = !report.dp;
}
else {
if (visibleReport) visibleReport.dp = false;
report.dp = true;
}
visibleReport = report
event.stopPropagation();
};
window.onclick = function(){
if (visibleReport)  visibleReport.dp = false;
visibleReport = null;
$scope.$apply();
};

这是一个正在工作的plunkerhttps://next.plnkr.co/edit/sWLxBGlF8D22nvYp?preview

最新更新