NewKidOnTheBlock NewKidOnTheBlock - 2 months ago 6
AngularJS Question

Angular - Separating variables for each show and hide element

I am trying to create a custom toggle accordion menu. I want to show and hide individual elements one by one. I have stripped the function down to the nuts and bolts.

I have made attempts to separate variables for each element I want to show and hide. Jsfiddle

This is my markup

<section ng-app="myApp">
<div ng-controller="accordionCtrl">
<div class="frq-accordion">
<div class="panel panel-default">
<!-- PANEL STARTS HERE-->
<div ng-click="frqToggle(hiddenToggleOne)" class="panel-heading">
<div class="panel-title">
<span>Some text goes here!</span>
</div>
</div><!-- PANEL HEADING ENDS HERE -->
<div id="collapseOne" ng-class="{isHidden: hiddenToggleOne}" class="panel-collapse">
<p>Hidden menu is open</p>
</div>
</div><!-- PANEL ENDS HERE -->
</div>
<!-- FRQ ACCORDION CONTAINER ENDS HERE -->

<div class="frq-accordion">
<div class="panel panel-default">
<!-- PANEL STARTS HERE-->
<div ng-click="frqToggle(hiddenToggleTwo)" class="panel-heading">
<div class="panel-title">
<span>Some text goes here!</span>
</div>
</div><!-- PANEL HEADING ENDS HERE -->
<div id="collapseTwo" ng-class="{isHidden: hiddenToggleTwo}" class="panel-collapse">
<p>Hidden menu is open</p>
</div>
</div><!-- PANEL ENDS HERE -->
</div>
<!-- FRQ ACCORDION CONTAINER ENDS HERE -->

<div class="frq-accordion">
<div class="panel panel-default">
<!-- PANEL STARTS HERE-->
<div ng-click="frqToggle(hiddenToggleThree)" class="panel-heading">
<div class="panel-title">
<span>Some text goes here!</span>
</div>
</div><!-- PANEL HEADING ENDS HERE -->
<div id="collapseThree" ng-class="{isHidden: hiddenToggleThree}" class="panel-collapse">
<p>Hidden menu is open</p>
</div>
</div><!-- PANEL ENDS HERE -->
</div>
<!-- FRQ ACCORDION CONTAINER ENDS HERE -->





ANGULAR

angular
.module('myApp')
.controller('futureCtrl', ['$scope', function($scope){


$scope.hiddenToggleOne = false;
$scope.hiddenToggleTwo = false;
$scope.hiddenToggleThree = false;
$scope.hiddenToggleFour = false;
$scope.hiddenToggleFive = false;

$scope.frqToggle = function (toggleElem) {
toggleElem = !toggleElem;
}

}]);

Answer

In your controller function frqToggle you are just setting the local variable toggleElem, and not modifying your scope variables.

You can dynamically set the scope variables:

$scope.frqToggle = function (toggleElem) {
  $scope[toggleElem] = !$scope[toggleElem];
}

You will then need to modify your ng-click to pass the name of the element rather than the element's value.

Comments