我在另一个页面上具有相同的功能,并且它的工作非常漂亮,但对于我的生活,我们无法弄清楚为什么它不能在第二个实现中工作:
如果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 $范围变量:
var regFields = ["userNameFirst","userNameLast","userPhone","userEmail","userAddress1",
"userAddress2","userCity","userState","userZip","userCountry","userCardType",
"userCardNumber","userCardMonth","userCardYear","userCardCSV"] ;
构建$ scope vars
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]) ;
}
}
}
答案 0 :(得分:0)
我解决了,但我不明白为什么,也许有人可以向我解释。
我原来的$ scope变量赋值如下,从localStorage读取数据:
var regFields = ["userNameFirst","userNameLast","userPhone","userEmail","userAddress1","userAddress2","userCity","userState","userZip","userCountry",
"userCardType","userCardNumber","userCardMonth","userCardYear","userCardCSV"] ;
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) ;
}
$scope[regFields[x]] = val ;
}
然后我将其改为:
$scope.userObj = {} ;
var regFields = ["userNameFirst","userNameLast","userPhone","userEmail","userAddress1","userAddress2","userCity","userState","userZip","userCountry",
"userCardType","userCardNumber","userCardMonth","userCardYear","userCardCSV"] ;
var userObj = {} ;
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) ;
}
$scope.userObj[regFields[x]] = val ;
}
然后我的所有模型都相应地改变了:
from: ng-model="userPhone" to ng-model="userObj.userPhone"
为什么在单个$ scope.object中分配所有内容而不是仅为从localStorage读入的每个密钥创建唯一的$ scope.var?
@charlietfl