3

I am trying to use ng-attr to conditionally add an attribute to an element. My code is something like this:

<label for="theID" 
       ng-attr-disabled="{{true || undefined}}"
       class="control-label">
  Some Label
</label>

What I get by inspecting the element is this:

<label translate="" for="theID" 
       ng-attr-disabled="{{true || undefined}}" 
       class="control-label ng-scope" disabled="disabled">
  Some Label
</label>

But expectation is:

<label translate="" for="theID" 
       ng-attr-disabled="{{true || undefined}}" 
       class="control-label ng-scope"
       disabled>
  Some Label
</label>

am I wrong altogether about how it works?

Thanks

georgeawg
  • 48,608
  • 13
  • 72
  • 95
Mark
  • 4,535
  • 7
  • 39
  • 76

3 Answers3

4

I don't think you should care about it, in your case. When value is falsy, disabled is not present. When value is truthy, is present - and it's all about presence in HTML about attributes like this (like required on inputs, validation care about presence required="false" makes input required). For example, you can style it dependent on attribute presence: MDN Attribute selectors.

Radek Anuszewski
  • 1,812
  • 8
  • 34
  • 62
  • 1
    Read my comment, please. – Mark Apr 14 '17 at 15:55
  • 1
    But I need to get it without any value. Is that possible? – Mark Apr 14 '17 at 16:12
  • @Mark I think you can only do it with plain DOM operation: http://stackoverflow.com/a/18774169/3368498 . You can try `label translate="" for="theID" id="label1" ng-init="$ctrl.addDisabled('label1')"` and inside `addDisabled(id)` you can do `$document.querySelector("#" + id).setAttribute("disabled", "")` – Radek Anuszewski Apr 14 '17 at 16:22
3

Angular has a special directive for the disabled attribute:

<label for="theID" 
        ̶n̶g̶-̶a̶t̶t̶r̶-̶d̶i̶s̶a̶b̶l̶e̶d̶=̶"̶{̶{̶t̶r̶u̶e̶ ̶|̶|̶ ̶u̶n̶d̶e̶f̶i̶n̶e̶d̶}̶}̶"̶
        ng-disabled="true || undefined"
        class="control-label">
    Some Label
</label>

From the Docs:

ngDisabled

  • directive in module ng

This directive sets the disabled attribute on the element (typically a form control, e.g. input, button, select etc.) if the expression inside ngDisabled evaluates to truthy.

A special directive is necessary because we cannot use interpolation inside the disabled attribute. See the interpolation guide for more info.

— AngularJS ng-disabled Directive API Reference

Community
  • 1
  • 1
georgeawg
  • 48,608
  • 13
  • 72
  • 95
0

If you want to disable element in Angular 4+ just add disabled attribute with your condition

<label for="theID" 
 disabled="condition"
 class="control-label">
    Some Label
</label>
MDF
  • 1,343
  • 1
  • 11
  • 14