Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS toggle divs visibility through button

I have a multiple sets of two divs and a button for each per page. The two divs contains alternating content that the button should handle switching visibility. I can't seem to think of an Angular solution that can be extensible to multiple separate instances in the page (my mind keeps wanting to get it done in JQuery).

I have created a JSFiddle example here.

You will see two divs p_table class with <span class="trigger">A</span>. The trigger should alternate the two p_table inside their parent div p_container.

like image 723
Alen Giliana Avatar asked Apr 06 '14 15:04

Alen Giliana


2 Answers

The key for how you are doing it is with ng-class, you can also do it with ng-show/ng-hide. Both implementations require no javascript, just a controller scope.

NG-CLASS: Choose a class based on a variable, which toggles on trigger click.

<div class="p_container">
  <p class="p_table" ng-class="{hidden:!show,chaldean:show}">This is actual content</p>
  <p class="p_table" ng-class="{hidden:show,chaldean:!show}">This is transliterated content</p> 
  <span class="trigger" ng-click="show=!show">A</span>
</div>

NG-SHOW/NG-HIDE: Show or hide on variable. This is the typical way of doing it.

<div class="p_container">
  <p class="p_table" ng-show="show">This is actual content</p>
  <p class="p_table" ng-hide="!show">This is transliterated content</p> 
  <span class="trigger" ng-click="show=!show">A</span>
</div>
like image 95
Zack Argyle Avatar answered Dec 31 '22 16:12

Zack Argyle


Here is how I did it, using ngHide and a tiny toggle function. Working demo Here. I hope this helps

My HTML Markup

<div ng-app="myApp" ng-controller="myCtrl">
            <div id="filter-row">
                <span
                    id="toggle-filter"
                    ng-click="toggleFilter()">
                    <i class="glyphicon glyphicon-heart"></i>
                </span>

                <div class="hiddenDiv" ng-hide="toggle">
                    <p>I am the hidden Div!</p>
                </div>
            </div>
</div>

My AngularJS Controller

var myApp = angular.module("myApp", []);
myApp.controller ("myCtrl", ['$scope', function($scope){
  $scope.toggle = true;
  $scope.toggleFilter = function() {
       $scope.toggle = $scope.toggle === false ? true : false;
  }
}]);
like image 41
AllJs Avatar answered Dec 31 '22 17:12

AllJs