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

后端 未结 2 1980
面向向阳花
面向向阳花 2020-12-31 11:25

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

相关标签:
2条回答
  • 2020-12-31 11:43

    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.

    0 讨论(0)
  • 2020-12-31 11:59

    Here is what I did. It's bit of a hack but works

    in css

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

    in html

    <a data-disabled="{{some boolean expersion}}" href="#2">Test</a>
    
    0 讨论(0)
提交回复
热议问题