Angular Directive for Check Number Input
In this blog, I'll create an angular directive to limit the length user can enter to the input text field. In the following example, the number directive default is 10, but the value could be overridden by the attribute.
The Angular Javascript Code
First, following code is based on angular1, the version is
1.4.8
. The below code all is doing are, setup the angular
module, set up the controller and the scope for the controller so that'll bind
to the HTML later. Next, we'll create directive numberField
to
the angular app.
var app = angular.module('myApp', []);
app.controller("myController", ['$scope', function($scope){
$scope.title = "my app number input";
$scope.mynumber = '';
}]);
app.directive('numberField', function () {
'use strict';
var NUMBER = /[^0-9]/g,
DEFAULT = 10;
return {
require: 'ngModel',
link: function (scope, element, attrs, modelCtrl) {
var lenth = attrs.numberLength || DEFAULT;
modelCtrl.$parsers.push(function (inputValue) {
if (inputValue == undefined) return ''
var transformedInput = inputValue.replace(NUMBER, '');
if (transformedInput.length <= lenth) {
// default number always 10 digits, otherwise looking for number-length attr
if (transformedInput != inputValue) {
modelCtrl.$setViewValue(transformedInput);
modelCtrl.$render();
}
return transformedInput;
}
var newValue = transformedInput.slice(0, -1);
modelCtrl.$setViewValue(newValue);
modelCtrl.$render();
return newValue;
});
}
};
});
The HTML
Once we have the Angular ready, we can use the angular as following. First
setup the app an controller to the HTML element. Then, next put angular
directive number-field
to the input field. Notice the second
input field has attribute number-length
as 6, because we use that
at angular code to check the length of the number.
<section ng-app="myApp" ng-controller="myController">
<h1>
{{title}}
</h1>
<div>
<input type="text" number-field ng-model="mynumber"/>
max length is 10
<br>
<input type="text" number-field ng-model="mynumber2" number-length="6"/>
max length is 6
<br>
</div>
</section>
Now, that's a simple way to create a number input field with a max length setting. You can also see above code from jsfiddler here. Or try the result from following.