Created
July 14, 2016 18:19
-
-
Save bonucci/a9bee7c0602b87735f969501638654ca to your computer and use it in GitHub Desktop.
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
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