问题
I am new to AngularJS and just started learning it. How can I load the JSON file into the script.js file without directly adding the entire data. Here is the code of the program:
<!DOCTYPE html>
<html ng-app="quizApp">
<head>
<meta charset="utf-8" />
<title>QuizApp</title>
<link rel="stylesheet" href="style.css" />
<script src="http://code.jquery.com/jquery-2.0.3.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.min.js"></script>
<script src="script.js"></script>
</head>
<body>
<div class="container">
<h1 class="title">QuizApp</h1>
<quiz/>
</div>
</body>
Plunkr.
回答1:
You need to correct the json pasted in ques.json
(by using quotes ""
) otherwise if you will invoke $http.get()
then you will get exception due to invalid json.
Once you will correct the json content in ques.json
then just use $http
and assign the result to questions variable.
E.g.
app.factory('quizFactory', function($http) {
var questions = [];
$http.get('ques.json').success(function(data) {
questions = data;
})
return {
getQuestion: function(id) {
if(id < questions.length) {
return questions[id];
} else {
return false;
}
}
};
});
Here is the demo
回答2:
$http.get('ques.json')
.then(function(result){
$scope.questions = result.data;
});
来源:https://stackoverflow.com/questions/30396533/load-json-data-into-the-factory-file