获得角度的JSON长度

时间:2017-10-28 07:14:18

标签: javascript angularjs json

{ "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在控制器中声明: 我尝试了几种解决方案,比如

  1. return Object.keys($scope.questions).length这是returning value: 6;显示console.log($scope.questions)后。我知道这是我的Parsed Object的属性数量。
  2. 然后在思考了一下后,我尝试了这个return $scope.questions.data.questions.length;这是有效的。但是,我的控制台上显示以下错误。
  3. 这是我的错误消息:

    Error message

    TypeError: Cannot read property 'data' of undefined.
    

3 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分: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字符串中的数组名称是问题

答案 2 :(得分:0)

从您分享的ScreenShot中可以理解,您进行了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.
  });