Woodchuck
Woodchuck

Reputation: 4414

AngularJS Disable ngClick

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?

Upvotes: 2

Views: 2547

Answers (3)

Abin Thaha
Abin Thaha

Reputation: 4633

Check this out, I have used the same method as @georgeawg used. The difference is that I have made it as a button format and used pointer-events: none so that no click event will be triggered from the .clickable

.clickable {
  cursor: pointer;
  display: inline-block;
  width: 200px;
  text-align: center;
  padding: 10px;
  background-color: #eee;
  transition: all 0.3s ease;
  margin: 10px 0;
}
.clickable:hover {
  background-color: #ddd;
}
.test {
  color: grey;
  pointer-events: none;
}
<script src="//unpkg.com/angular/angular.js"></script>
<body ng-app ng-init="count=0">
  <div>Count={{count}}</div>
   <div ng-click="count = count + 1" ng-class="{'test': stop}" class="clickable">Click Me</div>
   
   <div>
   <input type="checkbox" ng-model="stop">Stop counting
   </div>
</body>

Upvotes: 2

georgeawg
georgeawg

Reputation: 48968

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>

Upvotes: 3

orimdominic
orimdominic

Reputation: 1135

Try

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

The ng-disabled directive sets the disabled attribute of a form field (input, select, or textarea).

Upvotes: 1

Related Questions