Angular ng-class在input[text]生效但input[number]不生效问题求助
not-empty Class Issue in Your Angular Form Hey there! Let's get that not-empty class working for your zip code input. The problem here is pretty straightforward:
What's Going Wrong?
You're checking mailingzip.value in your ng-class directive, but your ng-model is bound directly to mailingzip—a primitive value (since it's a number), not an object with a value property. That means mailingzip.value is always undefined, so the not-empty class never gets applied.
The Fix
Instead of checking for .value, just check the mailingzip variable directly. When the user enters content, Angular will update this variable, and the class will toggle correctly.
Here's your updated code:
<div class="form-group" ng-class="{'not-empty': mailingzip}"> <input type="number" name="mailingzip" ng-minlength="5" ng-maxlength="5" ng-model="mailingzip" class="inputfield form-control" id="mailingzip" required> <label for="mailingzip" class="animated-label">Zip</label> </div>
A Quick Note About Zip Codes
If your use case allows for zip codes with leading zeros (like some US or international postal codes), using type="number" will strip those leading zeros automatically. For a better experience, switch to type="text" and add a regex pattern to enforce 5-digit input:
<div class="form-group" ng-class="{'not-empty': mailingzip}"> <input type="text" name="mailingzip" ng-pattern="/^\d{5}$/" ng-model="mailingzip" class="inputfield form-control" id="mailingzip" required> <label for="mailingzip" class="animated-label">Zip</label> </div>
That should do the trick! Test it out, and your not-empty class should apply as soon as the user starts typing in the zip field.
内容的提问来源于stack exchange,提问作者Tom

