AngularJS Show / Hide Toggle with NG-Repeat

I have a list of elements that when clicked should open one element, but now when I try to open one element it opens all the elements, and when I press it a second time it closes all the elements - can anyone please the advice where I am mistaking my code below . Thanks.

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; }; 
+5
source share
5 answers

Change your code as follows:

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

+12
source

ng-repeat creates a new area for each item. Each new region inherits toggleFilter and toggle from its parent. Right now, you are switching the switching state for the parent area. Thus, all child regions will receive the same value. If you want to switch the value in the scope of the child objects, just use this instead of $scope . Demo

 $scope.toggleFilter = function() { this.toggle = !this.toggle } 
+4
source

Add a parameter inside toggleFilter and make $ scope.toggle an array. For instance:

HTML

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

Js

 $scope.toggle = []; $scope.toggleFilter = function(inx) { $scope.toggle[inx] = $scope.toggle[inx] === false ? true : false; 

};

+2
source

hi, so I hope I get it right, but below is an example of code based on your question above. We got out and slightly changed our code.

HTML

 <div data-ng-repeat="item in items" layout="column"> <div layout="row"> <md-button class="md-primary" ng-click="toggleFilter()">{{buttonText}} </md-button> </div> <div ng-show="toggle"> <!-- Content --> </div> </div> 

Your JS will look like this

$ scope.toggle = false;

 $scope.buttonText = "Show"; $scope.toggleFilter = function(){ $scope.toggle = !$scope.toggle; $scope.buttonText = "Show"; if(toggle===true){ $scope.buttonText = "Hide"; } }; 

Hope this helps.

0
source

your HTML will look like this (only a change in HTML is required).

 <div ng-show=showMe> <!--content goes here --> <ul> <li ng-hide = "showMe">item1</li> <li ng-hide = "showMe">item2</li> <li ng-hide = "showMe">item3</li> <li ng-hide = "">item4</li> </ul> </div> 

I hope your question is answered. If not, leave a comment, I will be very happy to help.

0
source

All Articles