Angularjs toggle div visibility

All we need is an easy explanation of the problem, so here it is.

I am trying to toggle a div text on click of a button. I tried taking a scope variable and toggeling classname based on the variable. Where am I making the mistake here

<button ng-click="toggle()">test</button>
<div ng-class="{{state}}">
  hello test
</div>
function ctrl($scope) {
  $scope.state = vis;
  $scope.toggle = function() {
    state = !state;
  };
}
.vis {
  display: none;
}

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

You can simplify this a lot like so

<button ng-click="showDiv = !showDiv">test </button>
<div ng-show="showDiv" >
    hello test
</div>

Fiddle example

Unless you need the specific ng-class to toggle in which case you can do something like

<button ng-click="showDiv = !showDiv">test </button>
<div ng-class="{'vis' : showDiv }" >
    hello test
</div>

Fiddle example

(just make sure you’re using a newer version of angular for this)

Method 2

I have changed your directive..

html

    <button ng-click="toggle()">test </button>
<div ng-show="state" >
    hello test
</div>

Controller

function ctrl($scope) {    

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

see complete code here
http://jsfiddle.net/nw5ndzrt/345/

Method 3

Another approach…
Use ng-switch
You can toggle through multiple divs without the css hassle…

var myApp = angular.module('myApp',[]);

function MyCtrl($scope) {
 
}
<script src="https://code.angularjs.org/angular-1.0.1.js"></script>
<body ng-app="myApp">
<div ng-controller="MyCtrl">
	<button ng-click="showDiv = !showDiv">test </button>
	<div ng-switch="showDiv" >
	  <div ng-switch-default>
		hello you
	  </div>
	  <div ng-switch-when=true>
		hello me
	  </div>
	</div>
</div>
</body>  

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply