Search code examples
cssangularjsng-class

Apply ng-class based on length of Input


I have a input box where I can count characters. This input box is called ng-model="social.text". I can get that thing's length by going social.text.length.

Now, I want to subtract input.text.length from 280, so I have {{280-social.text.length}}

All this works without a hitch.

However! In the counter that I want to set up, I want to change its background color to yellow, if the math returns something under 100, and to red if it goes below 50.

So I have css classes set up that apply a background-color.

Now, I need to somehow apply these classes based on the length of the string.

<div class="chip" id="socialCounter">
    {{280-social.text.length}}
</div> 

So how do I apply ng-class to that? I'm quite lost here, so I'm sorry if I seem a bit incoherent.


Solution

  • You can use ng-class directive To achieve the same

    <!--css  -->
    
    .red{
      background-color:red;
    }
    .yellow{
      background-color:yellow;
    }
    
    <!-- html -->
    
    <div class="chip" id="socialCounter" ng-class="{'yellow':(280- social.text.length) <100 && (280- social.text.length) > 50  ,'red':(280- social.text.length) <50}" >
    {{280-social.text.length}}
    </div>
    

    plnkr demo