Skip to content

Instantly share code, notes, and snippets.

@bonucci
Created July 14, 2016 18:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bonucci/a9bee7c0602b87735f969501638654ca to your computer and use it in GitHub Desktop.
Save bonucci/a9bee7c0602b87735f969501638654ca to your computer and use it in GitHub Desktop.
angular.module('app')
.directive('flOnlyNumber', function() {
return {
restrict: 'EA',
require: 'ngModel',
link: function(scope, element, attrs, ngModel) {
scope.$watch(attrs.ngModel, function(newValue, oldValue) {
if (newValue) {
var spiltArray = String(newValue).split("");
if (attrs.isValid =="false"){
return false;
}else{
return true;
}
if (attrs.allowNegative == "false") {
if (spiltArray[0] == '-') {
newValue = newValue.replace("-", "");
ngModel.$setViewValue(newValue);
ngModel.$render();
}
}
if (attrs.allowDecimal == "false") {
newValue = parseInt(newValue);
ngModel.$setViewValue(newValue);
ngModel.$render();
}
if (attrs.allowDecimal != "false") {
//debugger;
if (attrs.decimalUpto) {
var splitChar = parseInt(newValue) && newValue.indexOf(',') > -1 ? ',' : '.'
var n = String(newValue).split(splitChar);
// var n = String(newValue).split(".");
if (n[1]) {
var n2 = n[1].slice(0, attrs.decimalUpto);
newValue = [n[0], n2].join(".");
ngModel.$setViewValue(newValue);
ngModel.$render();
}
}
}
if (spiltArray.length === 0) return;
if (spiltArray.length === 1 && (spiltArray[0] == '-' || (spiltArray[0] === '.' || spiltArray[0] === ','))) return;
// if (spiltArray.length === 1 && (spiltArray[0] == '-' || spiltArray[0] === '.')) return;
if (spiltArray.length === 2 && newValue === '-.') return;
/*Check it is number or not.*/
if (isNaN(newValue.replace(',', '.'))) {
ngModel.$setViewValue(oldValue || '');
ngModel.$render();
}
}
});
}
};
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment