在角度中获取 JSON 的长度
2017-10-28
3539
{ "questions": [
{
"text": "Which colors do you see in the rainbow?",
"answer": "A",
"A": "RED",
"B": "ORANGE",
"C": "YELLOW",
"D": "GREEN"
},
{
"text": "What is sanatbek's family name?",
"answer": "C",
"A": "Saidov",
"B": "Muhammadlatipov",
"C": "Matlatipov",
"D": "Boboyev"
},
{
"text": "How many members does this company have?",
"answer": "C",
"A": "3",
"B": "8",
"C": "9",
"D": "2"
}
]
}
这是我的
JSON
文件,我需要在
AngularJS
中获取问题的长度,如下所示:
function getQuestionCount() {
return $scope.questions.length;
}
此处
$scope.questions
在控制器中声明:
我尝试过多种解决方案,例如
-
return Object.keys($scope.questions).length
这是returning value: 6
; 在显示console.log($scope.questions)
之后。我明白这是我解析对象的属性数量。 -
然后经过一番思考,我尝试了这个
return $scope.questions.data.questions.length;
这是可行的。但是,我的控制台上显示以下错误。
这是我的错误消息:
TypeError: Cannot read property 'data' of undefined.
3个回答
从您分享的屏幕截图可以看出,您进行了 HTTP GET 调用来检索数据。 调用成功完成后,您可以在范围内的变量中设置问题长度。
$http({
method: 'GET',
url: '/someUrl'
}).then(function successCallback(response) {
$scope.questionsLenght = response.data.questions.length;
}, function errorCallback(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
Raghu
2017-10-28
如果在您的控制器中将 json 字符串设置为
$scope.questions = {
"questions": [
{
"text": "Which colors do you see in the rainbow?",
"answer": "A",
"A": "RED",
"B": "ORANGE",
"C": "YELLOW",
"D": "GREEN"
},
{
"text": "What is sanatbek's family name?",
"answer": "C",
"A": "Saidov",
"B": "Muhammadlatipov",
"C": "Matlatipov",
"D": "Boboyev"
},
{
"text": "How many members does this company have?",
"answer": "C",
"A": "3",
"B": "8",
"C": "9",
"D": "2"
}
]
};
尝试
$scope.questions.questions.length;
因为您的 json 字符串中的数组名称是问题
NTP
2017-10-28
您可以使用
for
循环获取长度:
for (var i = 0; i < $scope.questions.length; i++) {
$scope.data.push(angular.copy(types[i]));
}
Urvashi Bhatt
2017-10-28