angularjsng-showdirpagination

Show and Hide a <div> inside an ng-repeat with 'dirPagination' (AngularJS)


In this very site I've seen this question many times, but none of them works for me because of two things: I need the div to toggle when clicking the "options" button, but also to hide when clicking outside of the div; and I need it to work with dirPagination.

I saw this answer, it works fine but with one problem I just can't solve: it shows ALL the hidden divs at the same time, instead of only showing the one I clicked.

Here's my code:

<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>

And the JS to show the options:

//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();
    }
};

I've made a Plunker in case you wanna se it in action: my Plunker link
Can somebody help me with this issue? :(


Solution

  • You need to use a separate variable for each div you want to show. You could add the dp attribute to the report. There is no need to loop over the reports to hide them. You can just keep track of the currently visible report and hide it when another one is toggled.

    Here is the relevant 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>
    

    and 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();
    };
    

    Here is a working plunker https://next.plnkr.co/edit/sWLxBGlF8D22nvYp?preview