我有一个文本框。我想限制用户只复制粘贴数字。我不想复制粘贴字母和特殊字符。 我尝试了下面的代码而没有成功。
<!DOCTYPE html>
<html ng-app="plnk">
<head>
<script data-require="angular.js@*" data-semver="2.0.0" src="https://ajax.googleapis`enter code here`.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
<script src="app.js"></script>
</head>
<body>
<h1>Disable copy paste</h1>
for testing if angular is working {{1+1}}
<br/>
<input stopcopypaste ng-model="val" />
</body>
</html>
javascript:
var app = angular.module('plnk', []);
app.controller('MainCtrl', function($scope, $timeout) {
$scope.val = '1';
});
app.directive('stopcopypaste', function(){
return {
scope: {},
link:function(scope,element){
element.on('cut copy paste', function (event) {
key = event.keyCode || event.which;
if ((47 < key) && (key < 58) || key == 8 || key == 189 || key == 109) {
return true;
} else {
event.preventDefault();
return false;
}
})
})
}
};
});
我无法使用此代码限制字母和特殊字符。
答案 0 :(得分:1)
你可以使用ng-paste
指令并将控制器函数附加到它上面,如下所示:
app.js -
app.controller('MainCtrl', function($scope, $timeout) {
$scope.val = '1';
$scope.pasteOptions = function(e) {
var regex = /^\d+$/;
var pastedData = e.clipboardData.getData('text/plain');
if(pastedData.match(regex) === null) {
e.preventDefault();
return false;
}
};
});
HTML -
<body ng-controller="MainCtrl">
...
...
<input ng-paste="pasteOptions($event)" ng-model="val" />
对于副本,剪切 - ng-copy
,ng-cut
更新了plunker - https://plnkr.co/edit/pGk16GUGu9Tc0vTMvQND?p=preview