You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular ng-class在input[text]生效但input[number]不生效问题求助

Fixing the 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 08:22:31