Last active
February 24, 2021 03:45
-
-
Save lkatney/036653d08375365746294414e6c09791 to your computer and use it in GitHub Desktop.
Directive to handle number field scenarios on input[type=text]
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(function() { | |
'use strict'; | |
angular | |
.module('starter.services') | |
/** | |
* @ngdoc directive | |
* @name app.directive:numbersOnly | |
* @restrict 'A' | |
* @element ANY | |
* @description | |
* directive to only allows numbers | |
*/ | |
.directive('numbersOnly', function ($window) { | |
return { | |
require: 'ngModel', | |
link: function (scope, element, attr, ngModelCtrl) { | |
function fromUser(text) { | |
if (text) { | |
var allowDecimal = attr.allowDecimals; | |
var setDecimalPlaces = attr.setDecimalPlaces || 2; | |
var maxNumber = attr.maxNumber ? parseInt(attr.maxNumber) : undefined; | |
var transformedInput = text.replace(/[^0-9.]/g, ''); | |
if(transformedInput){ | |
var lst = transformedInput.split('.'); | |
var isDecimal; | |
var number, numberDigits; | |
var decimal, decimalDigits; | |
if(lst.length === 2){ | |
isDecimal = true; | |
number = lst[0] | |
numberDigits = number.length; | |
decimal = lst[1]; | |
decimalDigits = decimal.length; | |
}else if(lst.length === 1){ | |
isDecimal = false; | |
number = lst[0] | |
numberDigits = number.length; | |
} | |
if(maxNumber && numberDigits > maxNumber){ | |
if(isDecimal){ | |
transformedInput = number.substring(0, maxNumber) + '.' + decimal; | |
}else{ | |
transformedInput = number.substring(0, maxNumber); | |
} | |
} | |
if(allowDecimal && isDecimal){ | |
if(decimalDigits > setDecimalPlaces){ | |
transformedInput = (parseFloat(transformedInput).toFixed(setDecimalPlaces)).toString(); | |
} | |
}else{ | |
transformedInput = parseInt(transformedInput).toString(); | |
} | |
} | |
if (transformedInput !== text) { | |
ngModelCtrl.$setViewValue(transformedInput); | |
ngModelCtrl.$render(); | |
} | |
return transformedInput; | |
} | |
return undefined; | |
} | |
ngModelCtrl.$parsers.push(fromUser); | |
} | |
}; | |
}); | |
})(); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!-- Use attributes to configure input accordingly --> | |
<input type="text" placeholder="Enter number" numbers-only max-number="10" allow-decimals="true" set-decimal-places="3"/> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment