Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does angular's ng-disabled works with bootstrap's btn class?

I have an anchor tag on which, ng-disabled directive doesn't work at all.
It works on buttons but as soon as I add the Bootstrap's btn class to the anchor tag, Angular's ng-disabled starts working fine!

How is this working ?

like image 410
Amogh Talpallikar Avatar asked May 01 '14 13:05

Amogh Talpallikar


People also ask

How does ng-disabled work?

Definition and Usage The ng-disabled directive sets the disabled attribute of a form field (input, select, or textarea). The form field will be disabled if the expression inside the ng-disabled attribute returns true. The ng-disabled directive is necessary to be able to shift the value between true and false .

What does disabled mean in angular?

The ng-disabled Directive in AngularJS is used to enable or disable the HTML elements. If the expression inside the ng-disabled attribute returns true then the form field will be disabled or vice versa. It is usually applied on the form field (i.e, input, select, button, etc).


1 Answers

ngDisabled only works for elements that respond to the disabled attribute (inputs, textareas, radio buttons, button tags... etc.). In Bootstrap, you have to add the "disabled" class to your btn elements. That would look like this:

<div class="btn btn-default disabled">I'm a button!</div>

To do this in angular, define a variable in your directive/controller like so:

$scope.disableButtons = true;

Then use the angular ngClass to dynamically add the class based on the variable like so:

<div class="btn btn-default" ng-class="{'disabled': disableButtons}" ng-click="doSomething()">I'm a button!</div>

Every time you change the disableButtons variable within your scope, the button will appear to be disabled or enabled in the view depending on the value.

NOTE: Adding the disabled class to btn elements does not prevent JS click events from occuring. In order to do this, you have to write a hook in your doSomething() function like so:

$scope.doSomething = function() {
  if($scope.disableButtons) {
    return;
  }
  // Else, really do something
}

EDIT: It appears I didn't really answer the question. The real answer (I believe) is that disabled only works for .btn elements as well as links <a><a/> and list <li><li/> elements (... and probably a few more) because that's what Bootstrap defines it should work on. Here's the source from Bootstrap for btn elements:

.btn.disabled, .btn[disabled], fieldset[disabled] .btn {
  cursor: not-allowed;
  pointer-events: none;
  opacity: .65;
  filter: alpha(opacity=65);
  -webkit-box-shadow: none;
  box-shadow: none;
}

To get this working for anchor tags, you're going to have to write your own CSS replicating this, or even better, if you're using SASS to do something like @extend the styles.

like image 167
Mike Quinlan Avatar answered Oct 20 '22 17:10

Mike Quinlan