今天將奉獻一個在在幾個angularjs項目中抽離的angular組件 input mask。在我們開發中經常會對用戶的輸入進行控制,比如日期,貨幣格式,或者純數字格式之類的限制,這就是input mask的使用場景,在項目中也是會經常被提及需的需求之一。
當然在官方的angular-ui ui-utils中有一個相應的組件叫做ui-mask,但是其mask功能是很初級脆弱的。所以我希望能得到一個更強大的mask組件。我所知的jquery.inputmask就是這樣一個我所期望的強大的mask組件,所以我不必再去重造輪子,好的軟件就是為了不停被重復利用。所以寫了一個adapter,https://github.com/greengerong/green.inputmask4angular.
其使用如下,可以去下載項目查看其中的demo page。
<div class="hero-unit">
<h1>'Allo, 'Allo!</h1>
<div>
<h3>mask</h3>
<p>Mask: 99-9999999</p>
<input type="text" ng-model="test" input-mask="'mask'" mask-option="testoption"/>
<pre>{{ test | json }}</pre>
</div>
<div>
<h3>y-m-d</h3>
<p>Date: yyyy-MM-dd</p>
<input type="text" ng-model="test1" input-mask="'y-m-d'" format-option="dateFormatOption"/>
<pre>{{ test1 | json }}</pre>
</div>
<div>
<h3>Regex</h3>
<p>Email: "[a-zA-Z0-9._%-]+@[a-zA-Z0-9-]+\\.[a-zA-Z]{2,4}"</p>
<input type="text" ng-model="test3" input-mask="'Regex'"
mask-option="regexOption"/>
<pre>{{ test3 | json }}</pre>
</div>
<div>
<h3>Function</h3>
<p>"[1-]AAA-999" or "[1-]999-AAA"</p>
<input type="text" ng-model="test4" input-mask="functionOption"/>
<pre>{{ test4 | json }}</pre>
</div>
</div>
controller code:
'use strict';
angular.module('green.inputmaskApp')
.controller('MainCtrl', ["$scope", function ($scope) {
$scope.testoption = {
"mask": "99-9999999",
"oncomplete": function () {
console.log();
console.log(arguments,"oncomplete!this log form controler");
},
"onKeyValidation": function () {
console.log("onKeyValidation event happend! this log form controler");
}
}
//default value
$scope.test1 = new Date();
$scope.dateFormatOption = {
parser: function (viewValue) {
return viewValue ? new Date(viewValue) : undefined;
},
formatter: function (modelValue) {
if (!modelValue) {
return "";
}
var date = new Date(modelValue);
return (date.getFullYear() + "-" + date.getMonth() + "-" + date.getDate()).replace(/\b(\d)\b/g, "0$1");
},
isEmpty: function (modelValue) {
return !modelValue;
}
};
$scope.mask = { regex: ["999.999", "aa-aa-aa"]};
$scope.regexOption = {
regex: "[a-zA-Z0-9._%-]+@[a-zA-Z0-9-]+\\.[a-zA-Z]{2,4}"
};
$scope.functionOption = {
mask: function () {
return ["[1-]AAA-999", "[1-]999-AAA"];
}};
}]);
這里值列列舉了jquery.inputmask的簡單實用方式,更復雜的方式請移步到jquery.inputmask查看。
