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

如何在angular-ui-mask中停止掩码占位符(信用卡字段场景)

解决Angular-UI-Mask信用卡输入框占位符格式丢失问题

我来帮你搞定这个问题!你遇到的核心问题是:当点击输入框获得焦点时,angular-ui-mask会自动用你设置的space占位符填充掩码空位,把原来的Enter Card Number占位符给覆盖掉了。想要停止这个行为,利用指令自带的属性就能轻松解决。

最简单的解决方案:禁用掩码占位符替换

直接给输入框添加ui-mask-placeholder="false"属性,这样指令就不会在输入框聚焦时用掩码占位符替换你的原始placeholder文本。修改后的代码如下:

<div ng-app="myApp">
  <input class="form-control" type="text" 
         ng-model="accountNumber" 
         ui-mask="9999 9999 9999 9999 999" 
         placeholder="Enter Card Number" 
         ui-mask-placeholder-char="space"
         ui-mask-placeholder="false" />
</div>

添加这个属性后,不管输入框是否聚焦,只要内容为空,就会一直显示你设置的Enter Card Number占位符,不会被掩码的空格格式替换。

进阶:动态切换占位符(可选)

如果你想实现「失焦时显示掩码格式占位符,聚焦时显示原始提示文本」的效果,可以结合ng-focus、ng-blur和动态绑定ui-mask-placeholder来实现:

第一步:编写控制器逻辑

angular.module('myApp', ['ui.mask'])
.controller('CardInputController', function($scope) {
  // 控制是否显示掩码占位符
  $scope.useMaskPlaceholder = false;

  // 聚焦时切换为原始占位符
  $scope.onInputFocus = function() {
    $scope.useMaskPlaceholder = false;
  };

  // 失焦时,如果输入为空,切换回掩码占位符
  $scope.onInputBlur = function() {
    if (!$scope.accountNumber) {
      $scope.useMaskPlaceholder = true;
    }
  };
});

第二步:修改输入框代码

<div ng-app="myApp" ng-controller="CardInputController">
  <input class="form-control" type="text" 
         ng-model="accountNumber" 
         ui-mask="9999 9999 9999 9999 999" 
         placeholder="Enter Card Number" 
         ui-mask-placeholder-char="space"
         ui-mask-placeholder="{{useMaskPlaceholder}}"
         ng-focus="onInputFocus()"
         ng-blur="onInputBlur()" />
</div>

这样设置后,用户点击输入框时会显示Enter Card Number,离开输入框且未输入内容时,会显示掩码格式的空格占位符,兼顾了提示性和格式展示需求。

内容的提问来源于stack exchange,提问作者Mansi Teharia

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 09:38:24