angular directive for accepting input only as number

2

(In order to Enlarge images Please Right Click and Open images in New Tab)

hh1

 

Code Snippet=>

1)

<input type=”text” ng-model=”numberOfLabels” maxlength=”2″ valid-number />

2)

angular.module(“MyModule”).directive(‘validNumber’, function () {
return {
require: ‘?ngModel’,
link: function (scope, element, attrs, ngModelCtrl) {
if (!ngModelCtrl) {
return;
}

ngModelCtrl.$parsers.push(function (val) {
if (angular.isUndefined(val)) {
var val = ”;
}

var clean = val.replace(/[^/0-9]/g, ”);

var negativeCheck = clean.split(‘-‘);
var decimalCheck = clean.split(‘.’);
if (!angular.isUndefined(negativeCheck[1])) {
negativeCheck[1] = negativeCheck[1].slice(0, negativeCheck[1].length);
clean = negativeCheck[0] + ‘-‘ + negativeCheck[1];
if (negativeCheck[0].length > 0) {
clean = negativeCheck[0];
}

}

if (!angular.isUndefined(decimalCheck[1])) {
decimalCheck[1] = decimalCheck[1].slice(0, 2);
clean = decimalCheck[0] + ‘.’ + decimalCheck[1];
}

if (val !== clean) {
ngModelCtrl.$setViewValue(clean);
ngModelCtrl.$render();
}
return clean;
});

element.bind(‘keypress’, function (event) {
if (event.keyCode === 32) {
event.preventDefault();
}
});
}
};
});

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s