AngularJS Disable ngClick

老子叫甜甜 提交于 2020-01-25 00:21:06

问题


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?


回答1:


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>



回答2:


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>



回答3:


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).



来源:https://stackoverflow.com/questions/51845858/angularjs-disable-ngclick

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!