Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I toggle an ng-show in AngularJS based on a boolean?

People also ask

How do you toggle a Boolean in Javascript?

To toggle a boolean, use the strict inequality (! ==) operator to compare the boolean to true , e.g. bool !== true . The comparison will return false if the boolean value is equal to true and vice versa, effectively toggling the boolean.

How do I toggle a class in AngularJS?

The toggling of the class can be done in 2 ways, i.e., either specifying the value to 0 or 1, depending upon the condition satisfied, by initially defining the value as 0, or depending on the boolean value, i.e., true or false, with satisfying the required condition, by initially setting the value as true.

What is Ng-show and Ng hide?

The ng-show directive shows or hides the given HTML element based on the expression provided to the ng-show attribute. The ng-hide directive shows or hides the given HTML element based on the expression provided to the ng-hide attribute .

Is ng-show a directive?

AngularJS ng-show DirectiveThe ng-show directive shows the specified HTML element if the expression evaluates to true, otherwise the HTML element is hidden.


You just need to toggle the value of "isReplyFormOpen" on ng-click event

<a ng-click="isReplyFormOpen = !isReplyFormOpen">Reply</a>
 <div ng-show="isReplyFormOpen" id="replyForm">
   </div>

Basically I solved it by NOT-ing the isReplyFormOpen value whenever it is clicked:

<a ng-click="isReplyFormOpen = !isReplyFormOpen">Reply</a>

<div ng-init="isReplyFormOpen = false" ng-show="isReplyFormOpen" id="replyForm">
    <!-- Form -->
</div>

If based on click here it is:

ng-click="orderReverse = orderReverse ? false : true"

It's worth noting that if you have a button in Controller A and the element you want to show in Controller B, you may need to use dot notation to access the scope variable across controllers.

For example, this will not work:

<div ng-controller="ControllerA">
  <a ng-click="isReplyFormOpen = !isReplyFormOpen">Reply</a>

  <div ng-controller="ControllerB">
    <div ng-show="isReplyFormOpen" id="replyForm">
    </div>
  </div>

</div>

To solve this, create a global variable (ie. in Controller A or your main Controller):

.controller('ControllerA', function ($scope) {
  $scope.global = {};
}

Then add a 'global' prefix to your click and show variables:

<div ng-controller="ControllerA">
  <a ng-click="global.isReplyFormOpen = !global.isReplyFormOpen">Reply</a>

  <div ng-controller="ControllerB">
    <div ng-show="global.isReplyFormOpen" id="replyForm">
    </div>
  </div>

</div>

For more detail, check out the Nested States & Nested Views in the Angular-UI documentation, watch a video, or read understanding scopes.