2017-10-28 117 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字符串數組裏的名字是問題