angularjs - 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?
解决方案
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>
推荐阅读
- android - ConstraintLayout & BottomNavigationView,fragment和控件出现在下方。GoogleMaps v3 填充?
- unit-testing - 如何在 Clojure 测试中测试预期异常的消息?
- git - VScode 中解决 git 冲突的选项不出现
- postgresql - 具有内部变量值的 postgresql pset 标题
- c# - 正则表达式来屏蔽文本框文本?
- javascript - 对我的 express 后端 [MERN (React + Express)] 的多个过滤获取请求
- visual-studio-code - Plotly 安装了,但 VSCode 似乎不这么认为
- php - 会话仅在数组中存储一项
- r - 设置网络圆图的方向为顺时针
- c# - 我需要一个弯曲的矩形的透视变换