Adam Adam - 4 months ago 152
Javascript Question

AngularJS Show/Hide Toggle with NG-Repeat

I have a list of items which on click should open the single item, but currently when trying to open the single item it opens all items and on second click closed all the items - could somebody please advice where I am going wrong with my code below. Thank you.

HTML

<div data-ng-repeat="item in items" layout="column">
<div layout="row">
<md-button class="md-primary" ng-click="toggleFilter()">Item {{$index + 1}}</md-button>
</div>
<div ng-hide="toggle">
<!-- Content -->
</div>
</div>


JS

$scope.toggle = true;
$scope.toggleFilter = function() {
$scope.toggle = $scope.toggle === false ? true : false;
};

Answer

Edit Your code as following:

HTML

<div data-ng-repeat="item in items" layout="column">
  <div layout="row">
    <md-button class="md-primary" ng-click="toggleFilter(item)">Item {{$index + 1}}</md-button>
  </div>
  <div ng-hide="item.toggle">
    <!-- Content -->
  </div>
</div>

JS

$scope.toggleFilter = function(item) {
  item.toggle = !item.toggle;
};

Hope that works :)