2017-10-28 125 views
0
{ "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这样的:获取JSON的长度,角度

function getQuestionCount() { 
    return $scope.questions.length; 
} 

这里$scope.questions在控制器中声明: 我尝试了好几种像

  1. return Object.keys($scope.questions).length这是returning value: 6;显示后console.log($scope.questions)。我明白这是我的Parsed Object的属性数量。
  2. 然后想了一下,我试了这return $scope.questions.data.questions.length;这是工作。但是,以下错误显示在我的控制台上。

这里是我的错误消息:

Error message

TypeError: Cannot read property 'data' of undefined. 
+0

什么是'$ scope.questions'?它是三个对象的数组吗? –

+0

是的,它应该是从'questions'键取得的三个对象的数组。 Raghu先生的解决方案是解决我的问题的答案。 –

回答

0

从您共享可以理解的,你做了一个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. 
    }); 
+0

谢谢。当我从JSON解析出来的时候,我用全部的'response'来代替'response.data.questions'给我的全局变量! –

1

您可以通过使用for循环获取长度:

for (var i = 0; i < $scope.questions.length; i++) { 
    $scope.data.push(angular.copy(types[i])); 
    } 
0

如果你的控制器,你设置你的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字符串数组里的名字是问题