Search code examples
htmlangularjsng-classangularjs-material

Setting HTML element attribute conditionally


I have a data table that is in-line editable. One of the columns that is editable is an md-input field. I can easily enough add md-maxlength="80" to show the character counter. Given that this data table is done with UI-Grid (that code isn't relevant here), it applies the counter to all md-inputs in that column. What I really want is it to only show the character counter on focus. This is using Angular 1.X.

Ive got this so far, but I dont know if the expression to ng-class can accept anything except CSS classes.


<md-input
    ng-init="focused=false"
    ng-class="{'md-maxlength=80': focused}"
    ng-focus="focused=true"
    ng-blur="focused=false"
    ...
</md-input>

Solution

  • If I am understanding correctly, you want to add the md-maxlength="80" attribute when focused is true. Right now you are attempting to set the attribute as a CSS class which would make no sense since you can't have <div class="myClass md-maxlength='80'">

    Why not just set the value of the md-maxlenth property conditionally? Set the value to 80 when focused=true and set it to null otherwise. Possibly set it to 0 or some other value that makes sense for the md-input control since I'm not familiar with it.

    <md-input
        ng-init="focused=false"
        md-maxlength="focused ? 80 : null"
        ng-focus="focused=true"
        ng-blur="focused=false"
        ...
    </md-input>