Javascript 输入仅允许6位数字,逗号分隔后,角js中允许另外6位数字
大家好,我是angularjs的新手,我们希望实现一个只允许六位数字的输入文本框,输入六位数字后,用逗号分隔,然后添加并输入另外六位数字。你能帮帮我吗。我们现在拥有的示例代码是Javascript 输入仅允许6位数字,逗号分隔后,角js中允许另外6位数字,javascript,regex,angularjs,Javascript,Regex,Angularjs,大家好,我是angularjs的新手,我们希望实现一个只允许六位数字的输入文本框,输入六位数字后,用逗号分隔,然后添加并输入另外六位数字。你能帮帮我吗。我们现在拥有的示例代码是 **html** <div ng-controller="MyCtrl"> <input type="text" ng-model="number" required="required" numbers- only="numbers-only" /> </div> 我们找
**html**
<div ng-controller="MyCtrl">
<input type="text" ng-model="number" required="required" numbers-
only="numbers-only" />
</div>
我们找到的fiddler链接
编辑角度指令并将按键事件绑定到文本框元素。事件内部检查长度。如果长度为6,则在文本框中添加逗号并重新绑定新值。查看一下,将掩码设置为
9999999-9999999
,或者也可以使用只需在指令链接
中附加一个按键事件,然后检查输入长度并相应地执行操作。我没有修改您的代码,而是编写了自己的代码。这是一个
以下是HTML代码:
<div ng-app="myApp" ng-controller="MyCtrl">
<input type="text" ng-model="number" number-only required="required" />
</div>
以下是修改后的指令代码:
var app = angular.module('myApp', []);
app.controller('MyCtrl', ['$scope', function($scope) {
}])
app.directive('numberOnly', function() {
return {
restrict: 'A',
link: function(scope, elem, attrs) {
// Attach key press event
elem.bind('keypress', function(e) {
// Check if its a number
if (e.which >= 48 && e.which <= 57) {
var ar = scope.number.split(',');
if (ar[ar.length - 1].length >= 6) {
scope.number = scope.number + ',';
}
scope.$apply();
}
else {
e.preventDefault();
}
});
}
}
});
var-app=angular.module('myApp',[]);
app.controller('MyCtrl',['$scope',函数($scope){
}])
app.directive('numberOnly',function(){
返回{
限制:“A”,
链接:功能(范围、要素、属性){
//附加按键事件
元素绑定(“按键”,功能(e){
//检查它是否是一个数字
如果(e.which>=48&&e.which=6){
scope.number=scope.number+',';
}
作用域:$apply();
}
否则{
e、 预防默认值();
}
});
}
}
});
这段代码有什么问题吗?嘿,谢谢jade,提供了u-r代码,但我们无法删除在Firefox浏览器中输入的值,比如当我们输入backspace或删除它时,它不工作,在chrome中工作正常
var app = angular.module('myApp', []);
app.controller('MyCtrl', ['$scope', function($scope) {
}])
app.directive('numberOnly', function() {
return {
restrict: 'A',
link: function(scope, elem, attrs) {
// Attach key press event
elem.bind('keypress', function(e) {
// Check if its a number
if (e.which >= 48 && e.which <= 57) {
var ar = scope.number.split(',');
if (ar[ar.length - 1].length >= 6) {
scope.number = scope.number + ',';
}
scope.$apply();
}
else {
e.preventDefault();
}
});
}
}
});