How to make an ng-click event conditional?
I have this code inside ng-repeat:
<a href="#" class="disabled" ng-click="doSomething(object)">Do something</a>
How to make a condition that the button is disabled when it has class="disabled"
?
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
}
});
Solution 1:
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.
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.
Another way is to use lazy evaluation of expressions like isDisabled || action()
so action wouold not be called if isDisabled
is true.
Here goes both solutions: http://plnkr.co/edit/5d5R5KfD4PCE8vS3OSSx?p=preview
Solution 2:
We can add ng-click event conditionally without using disabled class.
HTML:
<div ng-repeat="object in objects">
<span ng-click="!object.status && disableIt(object)">{{object.value}}</span>
</div>
Solution 3:
I use the && expression which works perfectly for me.
For example,
<button ng-model="vm.slideOneValid" ng-disabled="!vm.slideOneValid" ng-click="vm.slideOneValid && vm.nextSlide()" class="btn btn-light-green btn-medium pull-right">Next</button>
If vm.slideOneValid
is false, the second part of the expression is not fired. I know this is putting logic into the DOM, but it's a quick a dirty way to get ng-disabled and ng-click to place nice.
Just remember to add ng-model to the element to make ng-disabled work.
Solution 4:
Basically ng-click
first checks the isDisabled
and based on its value it will decide whether the function should be called or not.
<span ng-click="(isDisabled) || clicked()">Do something</span>
OR read it as
<span ng-click="(if this value is true function clicked won't be called. and if it's false the clicked will be called) || clicked()">Do something</span>
Solution 5:
You could try to use ng-class
.
Here is my simple example:
http://plnkr.co/edit/wS3QkQ5dvHNdc6Lb8ZSF?p=preview
<div ng-repeat="object in objects">
<span ng-class="{'disabled': object.status}" ng-click="disableIt(object)">
{{object.value}}
</span>
</div>
The status is a custom attribute of object, you could name it whatever you want.
The disabled
in ng-class
is a CSS class name, the object.status
should be true
or false
You could change every object's status in function disableIt
.
In your Controller, you could do this:
$scope.disableIt = function(obj) {
obj.status = !obj.status
}