将json保存为对象数组

时间:2015-01-21 09:58:01

标签: angularjs

我有一个看似这样的角度应用程序:

(function (){
    var app = angular.module('world', []);

    app.controller('WorldController', function(){
        this.tabs = tabs; 
    });

    var tabs =[
    {   
        id: "1",
        name: "first tab name",
        title: "first tab title",
        content: "first tab cont"
    },
    {   
        id: "2",
        name: "orci, consectetuer",
        title: "sem elit, pharetra ut,",
        content: "augue scelerisque mollis. Phasellus"
    },
    {   
        id: "3",
        name: "rhoncus. Nullam velit dui, semper et, lacinia vitae,",
        title: "Nam porttitor",
        content: "tellus eu augue porttitor interdum. Sed auctor odio a purus."
    },
    {   
        id: "4",
        name: "nulla magna, malesuada vel, convallis in, cursus et, eros. Proin",
        title: "montes, nascetur ridiculus mus.",
        content: "Sed eget lacus. Mauris non dui nec urna suscipit nonummy."
    }
    ];

})();

我想从json加载整个tabs数组。我没有问题生成一个json并获取它,但我不知道如何将其转换为如上所示的格式。

当我尝试var tabs=jQuery.getJSON('myJson.json');时,会获取json,但它没有以我想要的格式加载。

如何将json转换为上面显示的数组格式?

虽然我的json看起来像那样 -

[
    {   
        "id": "1",
        "name": "mus. Proin vel arcu eu odio tristique pharetra.",
        "title": "faucibus",
        "content": "Donec dignissim magna a tortor. Nunc commodo auctor"
    },
    {   
        "id": "2",
        "name": "orci, consectetuer",
        "title": "sem elit, pharetra ut,",
        "content": "augue scelerisque mollis. Phasellus"
    },
    {   
        "id": "3",
        "name": "rhoncus. Nullam velit dui, semper et, lacinia vitae,",
        "title": "Nam porttitor",
        "content": "tellus eu augue porttitor interdum. Sed auctor odio a purus."
    },
    {   
        "id": "4",
        "name": "nulla magna, malesuada vel, convallis in, cursus et, eros. Proin",
        "title": "montes, nascetur ridiculus mus.",
        "content": "Sed eget lacus. Mauris non dui nec urna suscipit nonummy."
    }
];

1 个答案:

答案 0 :(得分:1)

在angular中使用$ http服务。例如,如果在包含json数据的同一文件夹中有data.json文件,则使用

app.controller('MainCtrl', function($scope, $http) {
  $http.get('data.json').success(function(data){
    $scope.fetched = data;
  })
});

这是plunker example