I am using ngChange in AngularJS to trigger a custom function that will remove any letters the user adds to the input.
我在AngularJS中使用ngChange来触发一个自定义函数,该函数将删除用户添加到输入中的任何字母。
<input type="text" name="inputName" data-ng-change="numbersOnly()"/>
The problem is that I need to target the input that triggered numbersOnly()
so that I can remove the letters entered. I have looked long and hard on Google and was unable to find anything regarding this.
问题是,我需要针对触发numbersOnly()的输入,这样我就可以删除输入的字母。我在谷歌上看了很长时间,没有找到任何关于这个的东西。
What can I do?
我能做什么?
14 个解决方案
#1
92
Easy way, use type="number" if it works for your use case:
简单的方法,使用type="number"如果它适用于你的用例:
<input type="number" ng-model="myText" name="inputName">
Another easy way: ng-pattern can also be used to define a regex that will limit what is allowed in the field. See also the "cookbook" page about forms.
另一种简单的方法是:ng-pattern也可以用来定义一个regex,它将限制字段中允许的内容。请参阅有关表格的“食谱”一页。
Hackish? way, $watch the ng-model in your controller:
很麻烦吗?好了,$关注控制器中的ng模型:
<input type="text" ng-model="myText" name="inputName">
Controller:
控制器:
$scope.$watch('myText', function() {
// put numbersOnly() logic here, e.g.:
if ($scope.myText ... regex to look for ... ) {
// strip out the non-numbers
}
})
Best way, use a $parser in a directive. I'm not going to repeat the already good answer provided by @pkozlowski.opensource, so here's the link: https://*.com/a/14425022/215945
最好的方法是在指令中使用$解析器。我不会重复@pkozlowski提供的已经很好的答案。这里是链接:https://*.com/a/14425022/215945
All of the above solutions involve using ng-model, which make finding this
unnecessary.
以上所有的解决方案都涉及到使用ng-model,这使得发现它是不必要的。
Using ng-change will cause problems. See AngularJS - reset of $scope.value doesn't change value in template (random behavior)
使用ng-change将导致问题。参见AngularJS -重新设置$scope。值不会改变模板中的值(随机行为)
#2
63
Using ng-pattern
on the text field:
在文本字段中使用ng-pattern:
<input type="text" ng-model="myText" name="inputName" ng-pattern="onlyNumbers">
Then include this on your controller
然后在控制器中包含这个
$scope.onlyNumbers = /^\d+$/;
#3
16
Here's my implementation of the $parser
solution that @Mark Rajcok recommends as the best method. It's essentially @pkozlowski.opensource's excellent $parser for text answer but rewritten to only allow numerics. All credit goes to him, this is just to save you the 5 minutes of reading that answer and then rewriting your own:
下面是我的$parser解决方案的实现,@Mark Rajcok推荐这是最好的方法。它本质上是@pkozlowski。opensource优秀的$解析器用于文本答案,但重写后只允许使用数字。所有的功劳都归他,这只是为了让你省下5分钟阅读答案然后重写自己的答案:
app.directive('numericOnly', function(){
return {
require: 'ngModel',
link: function(scope, element, attrs, modelCtrl) {
modelCtrl.$parsers.push(function (inputValue) {
var transformedInput = inputValue ? inputValue.replace(/[^\d.-]/g,'') : null;
if (transformedInput!=inputValue) {
modelCtrl.$setViewValue(transformedInput);
modelCtrl.$render();
}
return transformedInput;
});
}
};
});
And you'd use it like this:
你可以这样使用它:
<input type="text" name="number" ng-model="num_things" numeric-only>
Interestingly, spaces never reach the parser unless surrounded by an alphanumeric, so you'd have to .trim()
as needed. Also, this parser does NOT work on <input type="number">
. For some reason, non-numerics never make it to the parser where they'd be removed, but they do make it into the input control itself.
有趣的是,除非被字母数字包围,否则空间不会到达解析器,因此您必须根据需要使用.trim()。此外,该解析器不支持。由于某些原因,非数字符号永远不会出现在要删除它们的解析器中,但它们确实会进入输入控件本身。
#4
14
None of the solutions proposed worked fine for me, and after a couple of hours I finally found the way.
所有的解决方案对我都不起作用,几个小时后,我终于找到了方法。
This is the angular directive:
这是角度指示
angular.module('app').directive('restrictTo', function() {
return {
restrict: 'A',
link: function (scope, element, attrs) {
var re = RegExp(attrs.restrictTo);
var exclude = /Backspace|Enter|Tab|Delete|Del|ArrowUp|Up|ArrowDown|Down|ArrowLeft|Left|ArrowRight|Right/;
element[0].addEventListener('keydown', function(event) {
if (!exclude.test(event.key) && !re.test(event.key)) {
event.preventDefault();
}
});
}
}
});
And the input would look like:
输入是这样的:
<input type="number" min="0" name="inputName" ng-model="myModel" restrict-to="[0-9]">
The regular expression evaluates the pressed key, not the value.
正则表达式计算按下的键,而不是值。
It also works perfectly with inputs type="number"
because prevents from changing its value, so the key is never displayed and it does not mess with the model.
它还可以与input type="number"完美地工作,因为它阻止了它的值的更改,所以不会显示键,也不会影响模型。
#5
4
There are a few ways to do this.
有几种方法可以做到这一点。
You could use type="number"
:
您可以使用type =“数量”:
<input type="number" />
Alternatively - I created a reuseable directive for this that uses a regular expression.
或者,我为这个使用正则表达式创建了一个可重用的指令。
Html
Html
<div ng-app="myawesomeapp">
test: <input restrict-input="^[0-9-]*$" maxlength="20" type="text" class="test" />
</div>
Javascript
Javascript
;(function(){
var app = angular.module('myawesomeapp',[])
.directive('restrictInput', [function(){
return {
restrict: 'A',
link: function (scope, element, attrs) {
var ele = element[0];
var regex = RegExp(attrs.restrictInput);
var value = ele.value;
ele.addEventListener('keyup',function(e){
if (regex.test(ele.value)){
value = ele.value;
}else{
ele.value = value;
}
});
}
};
}]);
}());
#6
2
Here is a Plunker handling any situation above proposition do not handle.
By using $formatters and $parsers pipeline and avoiding type="number"
这是一个柱塞处理任何情况以上命题不处理。通过使用$格式化程序和$解析器管道,避免类型="number"
And here is the explanation of problems/solutions (also available in the Plunker) :
以下是问题/解决方案的解释(也可以在柱塞中找到):
/*
*
* Limit input text for floating numbers.
* It does not display characters and can limit the Float value to X numbers of integers and X numbers of decimals.
* min and max attributes can be added. They can be Integers as well as Floating values.
*
* value needed | directive
* ------------------------------------
* 55 | max-integer="2"
* 55.55 | max-integer="4" decimal="2" (decimals are substracted from total length. Same logic as database NUMBER type)
*
*
* Input type="number" (HTML5)
*
* Browser compatibility for input type="number" :
* Chrome : - if first letter is a String : allows everything
* - if first letter is a Integer : allows [0-9] and "." and "e" (exponential)
* Firefox : allows everything
* Internet Explorer : allows everything
*
* Why you should not use input type="number" :
* When using input type="number" the $parser pipeline of ngModel controller won't be able to access NaN values.
* For example : viewValue = '1e' -> $parsers parameter value = "".
* This is because undefined values are not allowes by default (which can be changed, but better not do it)
* This makes it impossible to modify the view and model value; to get the view value, pop last character, apply to the view and return to the model.
*
* About the ngModel controller pipelines :
* view value -> $parsers -> model value
* model value -> $formatters -> view value
*
* About the $parsers pipeline :
* It is an array of functions executed in ascending order.
* When used with input type="number" :
* This array has 2 default functions, one of them transforms the datatype of the value from String to Number.
* To be able to change the value easier (substring), it is better to have access to a String rather than a Number.
* To access a String, the custom function added to the $parsers pipeline should be unshifted rather than pushed.
* Unshift gives the closest access to the view.
*
* About the $formatters pipeline :
* It is executed in descending order
* When used with input type="number"
* Default function transforms the value datatype from Number to String.
* To access a String, push to this pipeline. (push brings the function closest to the view value)
*
* The flow :
* When changing ngModel where the directive stands : (In this case only the view has to be changed. $parsers returns the changed model)
* -When the value do not has to be modified :
* $parsers -> $render();
* -When the value has to be modified :
* $parsers(view value) --(does view needs to be changed?) -> $render();
* | |
* | $setViewValue(changedViewValue)
* | |
* --<-------<---------<--------<------
*
* When changing ngModel where the directive does not stand :
* - When the value does not has to be modified :
* -$formatters(model value)-->-- view value
* -When the value has to be changed
* -$formatters(model vale)-->--(does the value has to be modified) -- (when loop $parsers loop is finished, return modified value)-->view value
* |
* $setViewValue(notChangedValue) giving back the non changed value allows the $parsers handle the 'bad' value
* | and avoids it to think the value did not changed
* Changed the model <----(the above $parsers loop occurs)
*
*/
#7
1
DECIMAL
小数
directive('decimal', function() {
return {
require: 'ngModel',
restrict: 'A',
link: function(scope, element, attr, ctrl) {
function inputValue(val) {
if (val) {
var digits = val.replace(/[^0-9.]/g, '');
if (digits.split('.').length > 2) {
digits = digits.substring(0, digits.length - 1);
}
if (digits !== val) {
ctrl.$setViewValue(digits);
ctrl.$render();
}
return parseFloat(digits);
}
return "";
}
ctrl.$parsers.push(inputValue);
}
};
});
DIGITS
数字
directive('entero', function() {
return {
require: 'ngModel',
restrict: 'A',
link: function(scope, element, attr, ctrl) {
function inputValue(val) {
if (val) {
var value = val + ''; //convert to string
var digits = value.replace(/[^0-9]/g, '');
if (digits !== value) {
ctrl.$setViewValue(digits);
ctrl.$render();
}
return parseInt(digits);
}
return "";
}
ctrl.$parsers.push(inputValue);
}
};
});
angular directives for validate numbers
验证数字的角指令
#8
0
I know this is old, but I've created a directive for this purpose in case anyone is looking for an easy solution. Very simple to use.
我知道这是旧的,但我已经为此目的创建了一个指令,以防有人正在寻找一个简单的解决方案。使用起来非常简单。
You can check it out here.
你可以在这里看看。
#9
0
you may also want to remove the 0 at the beginning of the input... I simply add an if block to Mordred answer above because I cannot make a comment yet...
您可能还想在输入开始时删除0……我只是在上面的莫德雷德回答中添加了一个if块,因为我还不能做评论……
app.directive('numericOnly', function() {
return {
require: 'ngModel',
link: function(scope, element, attrs, modelCtrl) {
modelCtrl.$parsers.push(function (inputValue) {
var transformedInput = inputValue ? inputValue.replace(/[^\d.-]/g,'') : null;
if (transformedInput!=inputValue) {
modelCtrl.$setViewValue(transformedInput);
modelCtrl.$render();
}
//clear beginning 0
if(transformedInput == 0){
modelCtrl.$setViewValue(null);
modelCtrl.$render();
}
return transformedInput;
});
}
};
})
#10
0
Basic and clean HTML way
基本干净的HTML方式
<input type="number" />
#11
0
<input type="text" name="profileChildCount" id="profileChildCount" ng-model="profile.ChildCount" numeric-only maxlength="1" />
you can use numeric-only attribute .
您可以使用数字属性。
#12
0
Here is a pretty good solution to makes only allow enter number to the input
:
这里有一个很好的解决方案,只允许输入数字:
<input type="text" ng-model="myText" name="inputName" onkeypress='return event.charCode >= 48 && event.charCode <= 57'/>
#13
-1
I ended up creating a modified directive of the above code to accept input and change the format on the fly...
我最后创建了一个修改的指令,上面的代码接受输入并改变了格式。
.directive('numericOnly', function($filter) {
return {
require: 'ngModel',
link: function(scope, element, attrs, modelCtrl) {
element.bind('keyup', function (inputValue, e) {
var strinput = modelCtrl.$$rawModelValue;
//filter user input
var transformedInput = strinput ? strinput.replace(/[^,\d.-]/g,'') : null;
//remove trailing 0
if(transformedInput.charAt(0) <= '0'){
transformedInput = null;
modelCtrl.$setViewValue(transformedInput);
modelCtrl.$render();
}else{
var decimalSplit = transformedInput.split(".")
var intPart = decimalSplit[0];
var decPart = decimalSplit[1];
//remove previously formated number
intPart = intPart.replace(/,/g, "");
//split whole number into array of 3 digits
if(intPart.length > 3){
var intDiv = Math.floor(intPart.length / 3);
var strfraction = [];
var i = intDiv,
j = 3;
while(intDiv > 0){
strfraction[intDiv] = intPart.slice(intPart.length-j,intPart.length - (j - 3));
j=j+3;
intDiv--;
}
var k = j-3;
if((intPart.length-k) > 0){
strfraction[0] = intPart.slice(0,intPart.length-k);
}
}
//join arrays
if(strfraction == undefined){ return;}
var currencyformat = strfraction.join(',');
//check for leading comma
if(currencyformat.charAt(0)==','){
currencyformat = currencyformat.slice(1);
}
if(decPart == undefined){
modelCtrl.$setViewValue(currencyformat);
modelCtrl.$render();
return;
}else{
currencyformat = currencyformat + "." + decPart.slice(0,2);
modelCtrl.$setViewValue(currencyformat);
modelCtrl.$render();
}
}
});
}
};
})
})
#14
-1
<input type="text" ng-model="employee.age" valid-input input-pattern="[^0-9]+" placeholder="Enter an age" />
<script>
var app = angular.module('app', []);
app.controller('dataCtrl', function($scope) {
});
app.directive('validInput', function() {
return {
require: '?ngModel',
scope: {
"inputPattern": '@'
},
link: function(scope, element, attrs, ngModelCtrl) {
var regexp = null;
if (scope.inputPattern !== undefined) {
regexp = new RegExp(scope.inputPattern, "g");
}
if(!ngModelCtrl) {
return;
}
ngModelCtrl.$parsers.push(function(val) {
if (regexp) {
var clean = val.replace(regexp, '');
if (val !== clean) {
ngModelCtrl.$setViewValue(clean);
ngModelCtrl.$render();
}
return clean;
}
else {
return val;
}
});
element.bind('keypress', function(event) {
if(event.keyCode === 32) {
event.preventDefault();
}
});
}
}}); </script>
#1
92
Easy way, use type="number" if it works for your use case:
简单的方法,使用type="number"如果它适用于你的用例:
<input type="number" ng-model="myText" name="inputName">
Another easy way: ng-pattern can also be used to define a regex that will limit what is allowed in the field. See also the "cookbook" page about forms.
另一种简单的方法是:ng-pattern也可以用来定义一个regex,它将限制字段中允许的内容。请参阅有关表格的“食谱”一页。
Hackish? way, $watch the ng-model in your controller:
很麻烦吗?好了,$关注控制器中的ng模型:
<input type="text" ng-model="myText" name="inputName">
Controller:
控制器:
$scope.$watch('myText', function() {
// put numbersOnly() logic here, e.g.:
if ($scope.myText ... regex to look for ... ) {
// strip out the non-numbers
}
})
Best way, use a $parser in a directive. I'm not going to repeat the already good answer provided by @pkozlowski.opensource, so here's the link: https://*.com/a/14425022/215945
最好的方法是在指令中使用$解析器。我不会重复@pkozlowski提供的已经很好的答案。这里是链接:https://*.com/a/14425022/215945
All of the above solutions involve using ng-model, which make finding this
unnecessary.
以上所有的解决方案都涉及到使用ng-model,这使得发现它是不必要的。
Using ng-change will cause problems. See AngularJS - reset of $scope.value doesn't change value in template (random behavior)
使用ng-change将导致问题。参见AngularJS -重新设置$scope。值不会改变模板中的值(随机行为)
#2
63
Using ng-pattern
on the text field:
在文本字段中使用ng-pattern:
<input type="text" ng-model="myText" name="inputName" ng-pattern="onlyNumbers">
Then include this on your controller
然后在控制器中包含这个
$scope.onlyNumbers = /^\d+$/;
#3
16
Here's my implementation of the $parser
solution that @Mark Rajcok recommends as the best method. It's essentially @pkozlowski.opensource's excellent $parser for text answer but rewritten to only allow numerics. All credit goes to him, this is just to save you the 5 minutes of reading that answer and then rewriting your own:
下面是我的$parser解决方案的实现,@Mark Rajcok推荐这是最好的方法。它本质上是@pkozlowski。opensource优秀的$解析器用于文本答案,但重写后只允许使用数字。所有的功劳都归他,这只是为了让你省下5分钟阅读答案然后重写自己的答案:
app.directive('numericOnly', function(){
return {
require: 'ngModel',
link: function(scope, element, attrs, modelCtrl) {
modelCtrl.$parsers.push(function (inputValue) {
var transformedInput = inputValue ? inputValue.replace(/[^\d.-]/g,'') : null;
if (transformedInput!=inputValue) {
modelCtrl.$setViewValue(transformedInput);
modelCtrl.$render();
}
return transformedInput;
});
}
};
});
And you'd use it like this:
你可以这样使用它:
<input type="text" name="number" ng-model="num_things" numeric-only>
Interestingly, spaces never reach the parser unless surrounded by an alphanumeric, so you'd have to .trim()
as needed. Also, this parser does NOT work on <input type="number">
. For some reason, non-numerics never make it to the parser where they'd be removed, but they do make it into the input control itself.
有趣的是,除非被字母数字包围,否则空间不会到达解析器,因此您必须根据需要使用.trim()。此外,该解析器不支持。由于某些原因,非数字符号永远不会出现在要删除它们的解析器中,但它们确实会进入输入控件本身。
#4
14
None of the solutions proposed worked fine for me, and after a couple of hours I finally found the way.
所有的解决方案对我都不起作用,几个小时后,我终于找到了方法。
This is the angular directive:
这是角度指示
angular.module('app').directive('restrictTo', function() {
return {
restrict: 'A',
link: function (scope, element, attrs) {
var re = RegExp(attrs.restrictTo);
var exclude = /Backspace|Enter|Tab|Delete|Del|ArrowUp|Up|ArrowDown|Down|ArrowLeft|Left|ArrowRight|Right/;
element[0].addEventListener('keydown', function(event) {
if (!exclude.test(event.key) && !re.test(event.key)) {
event.preventDefault();
}
});
}
}
});
And the input would look like:
输入是这样的:
<input type="number" min="0" name="inputName" ng-model="myModel" restrict-to="[0-9]">
The regular expression evaluates the pressed key, not the value.
正则表达式计算按下的键,而不是值。
It also works perfectly with inputs type="number"
because prevents from changing its value, so the key is never displayed and it does not mess with the model.
它还可以与input type="number"完美地工作,因为它阻止了它的值的更改,所以不会显示键,也不会影响模型。
#5
4
There are a few ways to do this.
有几种方法可以做到这一点。
You could use type="number"
:
您可以使用type =“数量”:
<input type="number" />
Alternatively - I created a reuseable directive for this that uses a regular expression.
或者,我为这个使用正则表达式创建了一个可重用的指令。
Html
Html
<div ng-app="myawesomeapp">
test: <input restrict-input="^[0-9-]*$" maxlength="20" type="text" class="test" />
</div>
Javascript
Javascript
;(function(){
var app = angular.module('myawesomeapp',[])
.directive('restrictInput', [function(){
return {
restrict: 'A',
link: function (scope, element, attrs) {
var ele = element[0];
var regex = RegExp(attrs.restrictInput);
var value = ele.value;
ele.addEventListener('keyup',function(e){
if (regex.test(ele.value)){
value = ele.value;
}else{
ele.value = value;
}
});
}
};
}]);
}());
#6
2
Here is a Plunker handling any situation above proposition do not handle.
By using $formatters and $parsers pipeline and avoiding type="number"
这是一个柱塞处理任何情况以上命题不处理。通过使用$格式化程序和$解析器管道,避免类型="number"
And here is the explanation of problems/solutions (also available in the Plunker) :
以下是问题/解决方案的解释(也可以在柱塞中找到):
/*
*
* Limit input text for floating numbers.
* It does not display characters and can limit the Float value to X numbers of integers and X numbers of decimals.
* min and max attributes can be added. They can be Integers as well as Floating values.
*
* value needed | directive
* ------------------------------------
* 55 | max-integer="2"
* 55.55 | max-integer="4" decimal="2" (decimals are substracted from total length. Same logic as database NUMBER type)
*
*
* Input type="number" (HTML5)
*
* Browser compatibility for input type="number" :
* Chrome : - if first letter is a String : allows everything
* - if first letter is a Integer : allows [0-9] and "." and "e" (exponential)
* Firefox : allows everything
* Internet Explorer : allows everything
*
* Why you should not use input type="number" :
* When using input type="number" the $parser pipeline of ngModel controller won't be able to access NaN values.
* For example : viewValue = '1e' -> $parsers parameter value = "".
* This is because undefined values are not allowes by default (which can be changed, but better not do it)
* This makes it impossible to modify the view and model value; to get the view value, pop last character, apply to the view and return to the model.
*
* About the ngModel controller pipelines :
* view value -> $parsers -> model value
* model value -> $formatters -> view value
*
* About the $parsers pipeline :
* It is an array of functions executed in ascending order.
* When used with input type="number" :
* This array has 2 default functions, one of them transforms the datatype of the value from String to Number.
* To be able to change the value easier (substring), it is better to have access to a String rather than a Number.
* To access a String, the custom function added to the $parsers pipeline should be unshifted rather than pushed.
* Unshift gives the closest access to the view.
*
* About the $formatters pipeline :
* It is executed in descending order
* When used with input type="number"
* Default function transforms the value datatype from Number to String.
* To access a String, push to this pipeline. (push brings the function closest to the view value)
*
* The flow :
* When changing ngModel where the directive stands : (In this case only the view has to be changed. $parsers returns the changed model)
* -When the value do not has to be modified :
* $parsers -> $render();
* -When the value has to be modified :
* $parsers(view value) --(does view needs to be changed?) -> $render();
* | |
* | $setViewValue(changedViewValue)
* | |
* --<-------<---------<--------<------
*
* When changing ngModel where the directive does not stand :
* - When the value does not has to be modified :
* -$formatters(model value)-->-- view value
* -When the value has to be changed
* -$formatters(model vale)-->--(does the value has to be modified) -- (when loop $parsers loop is finished, return modified value)-->view value
* |
* $setViewValue(notChangedValue) giving back the non changed value allows the $parsers handle the 'bad' value
* | and avoids it to think the value did not changed
* Changed the model <----(the above $parsers loop occurs)
*
*/
#7
1
DECIMAL
小数
directive('decimal', function() {
return {
require: 'ngModel',
restrict: 'A',
link: function(scope, element, attr, ctrl) {
function inputValue(val) {
if (val) {
var digits = val.replace(/[^0-9.]/g, '');
if (digits.split('.').length > 2) {
digits = digits.substring(0, digits.length - 1);
}
if (digits !== val) {
ctrl.$setViewValue(digits);
ctrl.$render();
}
return parseFloat(digits);
}
return "";
}
ctrl.$parsers.push(inputValue);
}
};
});
DIGITS
数字
directive('entero', function() {
return {
require: 'ngModel',
restrict: 'A',
link: function(scope, element, attr, ctrl) {
function inputValue(val) {
if (val) {
var value = val + ''; //convert to string
var digits = value.replace(/[^0-9]/g, '');
if (digits !== value) {
ctrl.$setViewValue(digits);
ctrl.$render();
}
return parseInt(digits);
}
return "";
}
ctrl.$parsers.push(inputValue);
}
};
});
angular directives for validate numbers
验证数字的角指令
#8
0
I know this is old, but I've created a directive for this purpose in case anyone is looking for an easy solution. Very simple to use.
我知道这是旧的,但我已经为此目的创建了一个指令,以防有人正在寻找一个简单的解决方案。使用起来非常简单。
You can check it out here.
你可以在这里看看。
#9
0
you may also want to remove the 0 at the beginning of the input... I simply add an if block to Mordred answer above because I cannot make a comment yet...
您可能还想在输入开始时删除0……我只是在上面的莫德雷德回答中添加了一个if块,因为我还不能做评论……
app.directive('numericOnly', function() {
return {
require: 'ngModel',
link: function(scope, element, attrs, modelCtrl) {
modelCtrl.$parsers.push(function (inputValue) {
var transformedInput = inputValue ? inputValue.replace(/[^\d.-]/g,'') : null;
if (transformedInput!=inputValue) {
modelCtrl.$setViewValue(transformedInput);
modelCtrl.$render();
}
//clear beginning 0
if(transformedInput == 0){
modelCtrl.$setViewValue(null);
modelCtrl.$render();
}
return transformedInput;
});
}
};
})
#10
0
Basic and clean HTML way
基本干净的HTML方式
<input type="number" />
#11
0
<input type="text" name="profileChildCount" id="profileChildCount" ng-model="profile.ChildCount" numeric-only maxlength="1" />
you can use numeric-only attribute .
您可以使用数字属性。
#12
0
Here is a pretty good solution to makes only allow enter number to the input
:
这里有一个很好的解决方案,只允许输入数字:
<input type="text" ng-model="myText" name="inputName" onkeypress='return event.charCode >= 48 && event.charCode <= 57'/>
#13
-1
I ended up creating a modified directive of the above code to accept input and change the format on the fly...
我最后创建了一个修改的指令,上面的代码接受输入并改变了格式。
.directive('numericOnly', function($filter) {
return {
require: 'ngModel',
link: function(scope, element, attrs, modelCtrl) {
element.bind('keyup', function (inputValue, e) {
var strinput = modelCtrl.$$rawModelValue;
//filter user input
var transformedInput = strinput ? strinput.replace(/[^,\d.-]/g,'') : null;
//remove trailing 0
if(transformedInput.charAt(0) <= '0'){
transformedInput = null;
modelCtrl.$setViewValue(transformedInput);
modelCtrl.$render();
}else{
var decimalSplit = transformedInput.split(".")
var intPart = decimalSplit[0];
var decPart = decimalSplit[1];
//remove previously formated number
intPart = intPart.replace(/,/g, "");
//split whole number into array of 3 digits
if(intPart.length > 3){
var intDiv = Math.floor(intPart.length / 3);
var strfraction = [];
var i = intDiv,
j = 3;
while(intDiv > 0){
strfraction[intDiv] = intPart.slice(intPart.length-j,intPart.length - (j - 3));
j=j+3;
intDiv--;
}
var k = j-3;
if((intPart.length-k) > 0){
strfraction[0] = intPart.slice(0,intPart.length-k);
}
}
//join arrays
if(strfraction == undefined){ return;}
var currencyformat = strfraction.join(',');
//check for leading comma
if(currencyformat.charAt(0)==','){
currencyformat = currencyformat.slice(1);
}
if(decPart == undefined){
modelCtrl.$setViewValue(currencyformat);
modelCtrl.$render();
return;
}else{
currencyformat = currencyformat + "." + decPart.slice(0,2);
modelCtrl.$setViewValue(currencyformat);
modelCtrl.$render();
}
}
});
}
};
})
})
#14
-1
<input type="text" ng-model="employee.age" valid-input input-pattern="[^0-9]+" placeholder="Enter an age" />
<script>
var app = angular.module('app', []);
app.controller('dataCtrl', function($scope) {
});
app.directive('validInput', function() {
return {
require: '?ngModel',
scope: {
"inputPattern": '@'
},
link: function(scope, element, attrs, ngModelCtrl) {
var regexp = null;
if (scope.inputPattern !== undefined) {
regexp = new RegExp(scope.inputPattern, "g");
}
if(!ngModelCtrl) {
return;
}
ngModelCtrl.$parsers.push(function(val) {
if (regexp) {
var clean = val.replace(regexp, '');
if (val !== clean) {
ngModelCtrl.$setViewValue(clean);
ngModelCtrl.$render();
}
return clean;
}
else {
return val;
}
});
element.bind('keypress', function(event) {
if(event.keyCode === 32) {
event.preventDefault();
}
});
}
}}); </script>