我有一个函数用于验证前端中的某些字段,这是使用ng-click指令调用的。在 $ scope.validateAgainstStudent()中,我正在调用另一个函数 getStudentObj(value),它应该返回3个学生对象中的一个。
无论我到目前为止尝试过什么都不行。我得到的错误是 TypeError:无法读取属性' firstName'未定义的
$scope.student1 = {};
$scope.student2 = {};
$scope.student3 = {};
//This is being called from the frontend ng-click directive
$scope.validateAgainstStudent = function(value) {
console.log(getStudentObj(value).firstName);
if(getStudentObj(value).firstName==null || getStudentObj(value).lastName==null || getStudentObj(value).address==null){
alert('Please fill out all required fields');
} else{
//do something
}
}
};
//This should return the student object
function getStudentObj(value) {
if(value==1){
return $scope.student1;
}
if(value==2){
return $scope.student2;
}
if(value==3){
return $scope.student3;
}
};
我可以做这样的事情,没有函数 getStudentObj(value)的帮助,但由于学生对象的属性是相同的,我会得到很多重复的代码。即firstName,lastName ......等
$scope.student1 = {};
$scope.student2 = {};
$scope.student3 = {};
//This is being called from the frontend ng-click directive
$scope.validateAgainstStudent = function(value) {
if(value==1){
if($scope.student1.firstName==null || $scope.student1.lastName==null || $scope.student1.title==null){
alert('Please fill out all required fields');
} else{
//do something
}
}
if(value==2){
if($scope.student2.firstName==null || $scope.student2.lastName==null || $scope.student2.title==null){
alert('Please fill out all required fields');
} else{
//do something
}
}
if(value==2){
if($scope.student3.firstName==null || $scope.student3.lastName==null || $scope.student3.title==null){
alert('Please fill out all required fields');
} else{
//do something
}
}
};
答案 0 :(得分:0)
看起来value
匹配任何if
语句。您可以尝试添加console.log
以查看是否可以调试此问题。
//This should return the student object
function getStudentObj(value) {
if(value==1){
return $scope.student1;
}
if(value==2){
return $scope.student2;
}
if(value==3){
return $scope.student3;
}
console.log(value);
return {};
};
答案 1 :(得分:0)
您在getStudentObj(value)中输入的值不同于1,2和3.因此getStudentObj返回undefined。使用console.log(value)代替console.log(getStudentObj(value).firstName)来检查值。