【发布时间】:2016-10-12 17:26:10
【问题描述】:
我花了一段时间才弄清楚这一点,但是有人可以发布一种更简洁的方法来限制输入 type='number' 中的位数。问题之一是如果 $scope.variable = null....在输入字段中没有任何意义,则会引发错误。
<input type="number" model='modalName' ng-change="monitorLength('modalName',16)">
JS:
$scope.monitorLength = function (model,maxLength) {
if ($scope[model] != null) { // prevent error on empty input field
var len = $scope[model].toString() ; // convert to a string
if (len.length > maxLength) { //evaluate string length
$scope[model] = parseInt(len.substring(0, maxLength));
// convert back to number or warning is thrown on input value not being a number
}
}
}
然后我需要对此进行扩展以仅考虑数字,防止任何非数字字符包括“。”和“,”符号:
var reg = new RegExp(/^\d+$/) ;
$scope.monitorLength = function (modal,maxLength) {
if ($scope[modal] != null) {
var len = $scope[modal].toString() ;
if (len.length > maxLength) {
$scope[modal] = parseInt(len.substring(0, maxLength));
} else if (!reg.test(len)) {
$scope[modal] = parseInt(len.substring(0, len.length-2));
}
}
}
有没有办法提取负责调用 ng-change 的 ng-modal?所以呼叫只需:ng-change="monitorLength(10)"。然后在函数中以某种方式动态检索调用 ng-modal?
【问题讨论】:
-
你不能只在输入元素上使用
min和maxattributes 吗?很少有浏览器不支持该功能 -
不适用于 Angular,因为它包装元素并将它们绑定到 $scope 特定的 HTML 输入参数不起作用或被忽略。