AngularJS Disable ngClick

Issue

In AngularJS, is there any way to make an ng-click dependent upon a boolean?

For example, I’d like the following text (“Click”) to be clickable, but only when some scope property (e.g., $rootScope.enableClick) is true.

<div ng-click="count = count + 1" ng-init="count=0">Click</div>

Preferably, is there a straightforward way to do this without creating a custom directive?

Solution

Use the strange and wonderfull && logical operator in the ng-click expression:

<div ng-click="!stop && (count = count + 1)">Click me</div>

The DEMO

.clickable {
   cursor: pointer; 
}
<script src="//unpkg.com/angular/angular.js"></script>
<body ng-app ng-init="count=0">
   <div ng-click="!stop && (count = count + 1)" class="clickable" >Click Me</div>
   <div>Count={{count}}</div>
   <input type="checkbox" ng-model="stop">Stop counting<br>
</body>

Update

Or use a button with the ng-disabled directive:

<button ng-click="count = count + 1" ng-disabled="stop" >Click Me</button>

The ng-disabled directive does not work with <div> elements. The disabled property is not a global attribute. The ng-disabled directive only works with <input>, <button>, <textarea>, and <select> elements as those elements support the disabled property.

The DEMO

<script src="//unpkg.com/angular/angular.js"></script>
<body ng-app ng-init="count=0">
   <button ng-click="count = count + 1" ng-disabled="stop" >Click Me</button>
   <div>Count={{count}}</div>
   <input type="checkbox" ng-model="stop">Stop counting<br>
</body>

Answered By – georgeawg

Answer Checked By – Candace Johnson (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.