【发布时间】:2017-02-21 20:21:02
【问题描述】:
我在另一个页面上也有同样的功能,而且效果很好,但我一生都无法弄清楚为什么它不能在第二个实现中工作:
如果 userPhone 输入一开始是空白的,然后我开始输入一个数字,我得到的只是一遍又一遍的以下内容。但是为什么当我在输入字段中输入一个数字时 len.length = 0,从技术上讲,长度至少应该是 1。我看到发生了什么之后 - $scope.userPhone 被分配了 NaN - 因此新长度现在是3 ...但即使我输入更多数字,它也不会改变或更新。 $scope[itemID] ($scope.userPhone) 正确。
len: 0
THere! NaN
len: 3
THere! NaN
len: 3
THere! NaN
如果它以一个已经存在的数字开头,我删除一些或添加一些数字,我会得到以下信息:len: 10 - 一遍又一遍。无论可见长度是 0 3、5 还是 15。它就像 $scope.userPhone ($scope[itemID]) 永远不会更新输入字段。因为长度为 10,所以它永远不会进入第一个 IF 来截断长度。
HTML
<input type="number" id="userPhone" ng-model="userPhone" ng-change="monitorLength('userPhone',10)" ng-blur="verify('userPhone',10)">
要为模板创建的JS $scope 变量:
var regFields = ["userNameFirst","userNameLast","userPhone","userEmail","userAddress1",
"userAddress2","userCity","userState","userZip","userCountry","userCardType",
"userCardNumber","userCardMonth","userCardYear","userCardCSV"] ;
构建 $scope 变量
var reg = new RegExp(/^\d+$/) ;
for (var x=0;x<regFields.length;x++) {
var val = getDB(regFields[x]) ;
if (reg.test(val)) { // is a number, convert back to data type number
val = parseInt(val) ;
}
console.log("creating $scope: "+regFields[x]+ " w/ value: "+val+ " as "+typeof(val)) ;
$scope[regFields[x]] = val ;
}
$scope.monitorLength = function(itemID,maxLength) {
if ($scope[itemID] != null) {
var len = $scope[itemID].toString() ;
console.log("len: "+len.length) ;
if (len.length > maxLength) {
$scope[itemID] = parseInt(len.substring(0, maxLength));
console.log("Here! " + $scope[itemID]) ;
} else if (!reg.test(len)) {
$scope[itemID] = parseInt(len.substring(0, len.length-1));
console.log("THere! " + $scope[itemID]) ;
}
}
}
【问题讨论】:
-
需要提供minimal reproducible example。我们不知道您的范围内有什么,也无法重现您的问题。你也打破了在
ng-model中不使用对象的黄金法则 -
首先不要发送itemID,而是发送实际项目
ng-change="monitorLength(userPhone, 10)。然后不要覆盖范围[itemID]中的内容,而是使用另一个变量:var update = +(String(item).substring(0, maxLength)); console.log(update); -
@floribon - 您的方法正在将 userPhone 的值传递给 monitorLength 函数......但是一旦进入并提供了更新,那么您如何传递新的
update(如果超过 maxLength)回到正确的 $scope 变量? -
@rolinger 啊确实如此,所以你可以保留你正在做的事情。但是您应该添加更多日志以了解为什么会得到 NaN。当您记录其长度时,
len中的内容是什么? -
还可以尝试将 monitorLength 函数中的内容包裹在 $timeout 周围:
$scope.monitorLength = function(itemID,maxLength) { $timeout(function() { ..... }); }
标签: javascript angularjs input angularjs-scope angular-ngmodel