将json数据加载到工厂文件中 [英] Load json data into the factory file

查看:36
本文介绍了将json数据加载到工厂文件中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 AngularJS 的新手,刚刚开始学习它.如何在不直接添加整个数据的情况下将 JSON 文件加载到 script.js 文件中.这是程序的代码:

<html ng-app="quizApp"><头><meta charset="utf-8"/><title>测验应用</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><身体><div class="容器"><h1 class="title">QuizApp</h1><测验/>

Plunkr.

解决方案

您需要更正 ques.json 中粘贴的 json(使用引号 ""),否则如果你调用 $http.get() 那么你会因为无效的 json 得到异常.

一旦您将更正 ques.json 中的 json 内容,只需使用 $http 并将结果分配给 questions 变量.

例如

app.factory('quizFactory', function($http) {var 问题 = [];$http.get('ques.json').success(function(data) {问题 = 数据;})返回 {获取问题:功能(ID){if(id < questions.length) {返回问题[id];} 别的 {返回假;}}};});

这是演示

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.

解决方案

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

这篇关于将json数据加载到工厂文件中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆