如何使 ng-click 事件有条件? [英] How to make an ng-click event conditional?
问题描述
我在 ng-repeat 中有这个代码:
I have this code inside ng-repeat:
<a href="#" class="disabled" ng-click="doSomething(object)">Do something</a>
当有class="disabled"
时,如何设置按钮被禁用的条件?
How to make a condition that the button is disabled when it has class="disabled"
?
或者有没有办法在 Javascript 中做到这一点,看起来像:
Or is there a way to do it in Javascript so that will look like:
$('.do-something-button').click(function(){
if (!$(this).hasClass('disabled')) {
do something
}
});
推荐答案
在除指令之外的任何地方使用 DOM 进行操作(包括检查属性)都不好.您可以在范围内添加一些值,指示是否应禁用链接.
It is not good to manipulate with DOM (including checking of attributes) in any place except directives. You can add into scope some value indicating if link should be disabled.
但另一个问题是 ngDisabled 对表单控件以外的任何东西都不起作用,因此您不能将它与 一起使用,但您可以将它与
But other problem is that ngDisabled does not work on anything except form controls, so you can't use it with <a>, but you can use it with <button> and style it as link.
另一种方法是使用像 isDisabled || 这样的表达式的惰性求值action()
所以如果 isDisabled
为真,动作不会被调用.
Another way is to use lazy evaluation of expressions like isDisabled || action()
so action wouold not be called if isDisabled
is true.
这里有两种解决方案:http://plnkr.co/edit/5d5R5KfD4PCE8vS3OSSx?p=preview
这篇关于如何使 ng-click 事件有条件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!