15

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;
}
Community
  • 1
  • 1
Kurkula
  • 6,386
  • 27
  • 127
  • 202

3 Answers3

33

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)

ajmajmajma
  • 13,712
  • 24
  • 79
  • 133
  • @Chandana which part are you referring to? Becuase that fiddle you are using is not hooked up correctly. – ajmajmajma Sep 28 '15 at 19:23
  • 1
    @Chandana you did not bootstrap that fiddle, check my example for working fiddle. I have added working fiddle examples for both methods. – ajmajmajma Sep 28 '15 at 19:26
18

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/

Kashif Mustafa
  • 1,152
  • 6
  • 20
2

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>  
Gi1ber7
  • 632
  • 1
  • 11
  • 22