我有两个 HTML 输入(type="email"
、type="number"
),我的 Angular 应用使用 $formatters
监视它们> 和 $parsers
。错误存储在数组中,当用户插入包含“@gmail”的电子邮件时,错误将从数组中删除。
app.controller('form1Controller', function($scope, UserService) {
$scope.formCompleted = false;
$scope.errors = UserService.errors;
//handle the user email input.
$scope.storeEmailErr = function(data) {
var correctKey = "@gmail";
var key = "#userEmail";
var res = {};
if (data != null) {
res = $scope.handleError(data, emailIn, correctKey, key, $scope.errors);
$scope.errors = res[0];
UserService.errors = res[0];
emailIn = res[1];
}
};
//handle the user email input.
$scope.storeIdErr = function(data) {
var correctKey = "0000";
var key = "#userId";
var res = {};
if (data != null) {
res = $scope.handleError(data, idIn, correctKey, key, $scope.errors);
$scope.errors = res[0];
idIn = res[1];
}
};
}
这是在数组中添加和删除错误的代码。我想这就是问题所在
function theIndexOf(val) {
console.log("find index in array of length: " + errorsDescription.length)
for (var i = 0; i < errorsDescription.length; i++) {
if (errorsDescription[i].selector === val) {
return i;
}
}
}
app.run(function($rootScope){
$rootScope.handleError = function(data, elemIn, correctKey, key, errorArray){
var idx = theIndexOf(key);
console.log("get index >>>>> " + idx);
var obj = errorsDescription[idx];
//if user didn't put correct word i.e. @gmail or 0000
if (data.indexOf(correctKey) < 0) {
if (!elemIn) {
errorArray.push(obj);
elemIn = true;
}
} else {
if (elemIn) {
$.each(errorArray, function(i){
if(errorArray[i].selector === key) {
errorArray.splice(i, 1);
elemIn = false;
}
});
}
}
return [errorArray, elemIn];
}
});
问题是,当我插入“test@gmail.com”时,错误从数组中删除,当我再次插入正确的数据时,它告诉我无法读取未定义的“yyy”属性。
这是我的笨蛋。 https://plnkr.co/edit/l0ct4gAh6v10i47XxcmT?p=preview
在 plunker 中,输入字段 'test@gmail' 和 test0000 作为编号,然后删除数据,然后再次插入相同的数据以查看问题
如有任何帮助,我们将不胜感激!
最佳答案
编辑:在这里工作 plunkr:https://plnkr.co/edit/8DY0Cd5Pvt6TPVYHbFA4
问题在这里:
var obj = errorsDescription[idx];
//if user didn't put correct word i.e. @gmail or 0000
if(data.indexOf(correctKey) < 0){
// console.log("You must put correct word");
if(!elemIn){
errorArray.push(obj);
elemIn = true;
}
}
当您的个人号码错误被移除时,上述逻辑将未定义插入您的 errorArray(因为 elemIn 为假)。您的 storeIdErr 方法:
$scope.storeIdErr = function(data){
var correctKey = "0000";
var key = "#userId";
var res = {};
if(data != null){
res = $scope.handleError(data, idIn, correctKey, key, $scope.errors);
$scope.errors = res[0];
idIn = res[1];
}
};
读取此值 (res[0]) 并将其存储在 $scope.errors 中,最终在下一个输入事件上迭代:
function theIndexOf(val){
console.log("find index in array of length: " + errorsDescription.length)
for(var i = 0; i < errorsDescription.length; i++){
if(errorsDescription[i].selector === val){
return i;
}
}
}
由于您的工厂在询问错误时返回该对象。要解决此问题,您应该保留一个您永远不会从中删除的静态列表,该列表提供了错误定义。这是您在第一个代码块中推送到 errorArray 时应该引用的内容。
关于javascript - 无法读取未定义的 'xyxyx' 属性,即使元素存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37333115/