将JSON数据存储到变量中 [英] Store JSON data into a variable

查看:290
本文介绍了将JSON数据存储到变量中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是AngularJS的新手.我只想将JSON文件数据加载到工厂中的变量中.

I am new to AngularJS. I just want to load the JSON file data into a variable that is located in factory.

myApp.factory('quizFactory', function () {
    var questions = [
        {
            "setId":1,
            "question":"What is the value of the 7 in the following number? 850,765",
            "options": ["70", "7", "7000", "700"],
            "answer": 3
        },
        {
            "setId":2,
            "question":"Is 7 & 9 even or odd?",
            "options": ["Even", "Odd", "Can't Say", "Dont know"],
            "answer": 1
        },
        {
            "setId":3,
            "question":"In the number 5,281,946 what is the value of the 3rd place?",
            "options": ["100", "10,000", "1,000,000", "1,000"],
            "answer": 0 
        },
        {
            "setId":4,
            "question":"Is 12 + 50 even or odd?",
            "options": ["Even", "Odd", "Can't Say", "Dont know"],
            "answer": 0 
        },
        {
            "setId":5,
            "question":"What does the 3 represent in the number below? 3051",
            "options": ["3", "30", "300", "3000"],
            "answer": 3 
        }
    ];

    return {
        getQuestion: function(id) {
            if(id < questions.length) {
                return questions[id];
            } else {
                return false;
            }
        }
    };
});

上面的代码存储在app.js文件中,我的JSON文件与上面的代码相同.

The above code is stored in app.js file and my JSON file is same as the above.

[


{
        "setId":1,
        "question":"What is the value of the 7 in the following number? 850,765",
        "options": ["70", "7", "7000", "700"],
        "answer": 3
    },
    {
        "setId":2,
        "question":"Is 7 & 9 even or odd?",
        "options": ["Even", "Odd", "Can't Say", "Dont know"],
        "answer": 1
    },
    {
        "setId":3,
        "question":"In the number 5,281,946 what is the value of the 3rd place?",
        "options": ["100", "10,000", "1,000,000", "1,000"],
        "answer": 0 
    },
    {
        "setId":4,
        "question":"Is 12 + 50 even or odd?",
        "options": ["Even", "Odd", "Can't Say", "Dont know"],
        "answer": 0 
    },
    {
        "setId":5,
        "question":"What does the 3 represent in the number below? 3051",
        "options": ["3", "30", "300", "3000"],
        "answer": 3 
    }
];

我也尝试过这个问题.

推荐答案

您可以使用 $ http 读取json文件.例如

You can use $http to read json file. E.g.

$http.get('someFile.json').success(function(data) {    
        questions = data;
    });    

这篇关于将JSON数据存储到变量中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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