Search code examples
angularjscodepen

Create local json in Codepen for AngularJS


The following tutorial points to an external json file. But it is blocked by CORS policy. How can I declare the object locally in order to populate the web table? Codepen: https://codepen.io/centem/pen/Rwbmmdy Thank you.

var app = angular.module('myApp', []);
    app.controller('myController',
        function ($scope, $http) {

            var request = {
                method: 'get',
                url: 'https://www.encodedna.com/angularjs/tutorial/birds.json',
                dataType: 'json',
                contentType: "application/json"
            };

            $scope.arrBirds = new Array;

            $http(request)
                .success(function (jsonData) {
                    $scope.arrBirds = jsonData;
                    $scope.list = $scope.arrBirds;
                })
                .error(function () {

                });
        });

Solution

  • Simply declare the variable you want with the json data:

    $scope.list = [
    {
       "ID": "001",
       "Name": "Eurasian Collared-Dove",
       "Type": "Dove"
    },
    {
        "ID": "002",
        "Name": "Bald Eagle",
        "Type": "Hawk"
    },
    {
        "ID": "003",
        "Name": "Cooper's Hawk",
        "Type": "Hawk"
    },
    {
        "ID": "004",
        "Name": "Bell's Sparrow",
        "Type": "Sparrow"
    },
    {
        "ID": "005",
        "Name": "Mourning Dove",
        "Type": "Dove"
    },
    {
        "ID": "006",
        "Name": "Rock Pigeon",
        "Type": "Dove"
    },
    {
        "ID": "007",
        "Name": "Abert's Towhee",
        "Type": "Sparrow"
    },
    {
        "ID": "008",
        "Name": "Brewer's Sparrow",
        "Type": "Sparrow"
    },
    {
        "ID": "009",
        "Name": "Canyon Towhee",
        "Type": "Sparrow"
    },
    {
        "ID": "010",
        "Name": "Black Vulture",
        "Type": "Hawk"
    }];