1

In one of my application, I have a requirement to add a specific class when it has any data irrespective of it's input type (email, text) using AngularJS:

In this plunk, just type any thing in the text box to change the border color.

code for reference

<body ng-app="">
    <input type='text' ng-model='Custom' ng-class="{red : Custom.length}">
    <label ng-bind='Custom'></label>
</body>

In a similar way I want it for all the input types.

In case of email field. When user typed wrong email, it's not working because model will not get value when it is invalid.

1

2 Answers 2

1

Angular not binding value to model until model is valid so in case of input type filed lengthwill be 0 until you type in proper email. But you can do that using $viewValue value please see demo below

.red {
  border-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<body ng-app="">
  <form name="myform">
    <input type='text' ng-model='Custom' ng-class="{red : Custom.length}">
    <input type='email' ng-model='email' ng-class="{red : myform.email.$viewValue}" name="email">

    <label ng-bind='Custom'></label>
  </form>
</body>

Sign up to request clarification or add additional context in comments.

Comments

0

This happens because until the input contains a valid email address ng-model is empty.

One way to overcome it is to check the $viewValue variable like this:

<form name="myForm" novalidate>
    <input name="email" type='email' ng-model='email' 
           ng-class="{red : myForm.email.$viewValue.length}">
</form>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.