Load json data into the factory file

旧街凉风 提交于 2019-12-11 23:33:53

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!