首页 > 解决方案 > 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?

标签: angularjsangularjs-ng-click

解决方案


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>


推荐阅读