Drew Sanislo Drew Sanislo - 4 years ago 148
Javascript Question

Loading data from JSON file in to Javascript object

I am trying to access the data from my JSON file to be used within my controller for further manipulation using Angular. To start, here are the first couple entries of the file 'cards.json'

{ "TheGrandTournament": [
{
"name": "Buccaneer",
"cardSet": "The Grand Tournament",
"type": "Minion",
"rarity": "Common",
"cost": 1,
"attack": 2,
"health": 1,
"text": "Whenever you equip a weapon, give it +1 Attack.",
"collectible": true,
"playerClass": "Rogue",
"img": "http://wow.zamimg.com/images/hearthstone/cards/enus/original/AT_029.
},
{
"name": "Competitive Spirit",
"cardSet": "The Grand Tournament",
"type": "Spell",
"rarity": "Rare",
"cost": 1,
"text": "<b>Secret:</b> When your turn starts, give your minions +
"collectible": true,
"playerClass": "Paladin",
"img": "http://wow.zamimg.com/images/hearthstone/cards/enus/original/AT_073.
"mechanics": [{"name": "Secret"}]
}, ...
]}


I have had success with accessing the information from my view using this code

<div ng-controller="CardCtrl">
<button id="loadbtn" ng-click="load()">Load</button><br>
<div ng-repeat="cards in data.TheGrandTournament | limitTo:2">
<pre>{{ cards.name }}</pre>
</div>
</div


My controller looks like this:

angular.module('cards', []).controller('CardCtrl', ['$scope', '$http',
function ($scope, $http) {
$scope.method = 'GET';
$scope.url = 'cards.json';

$scope.load = function() {
$scope.code = null;
$scope.response = null;

$http({method: $scope.method, url: $scope.url}).
then(function(response) {
$scope.data = response.data;
console.log("Read file", $scope.url, "successfully.");
}, function(response) {
$scope.data = response.data || "Request failed";
console.log("Error reading", $scope.url, ".");
});
};

$scope.cardData = angular.fromJson($scope.data[0]);
console.log($scope.cardData);

}]);


The error returned when trying to output $scope.cardData to a console log is

"TypeError: Cannot read property '0' of undefined".


I tried then parsing the data from the json object using angular.fromJson() but it is not working as I am intending.

Answer Source

You should move $scope.data into the success callback of the promise:

$http({method: $scope.method, url: $scope.url}).
  then(function(response) {
    $scope.cardData = response.data.TheGrandTournament;
    console.log("Read file", $scope.url, "successfully.");
    console.log($scope.cardData);
  }, function(response) {
    $scope.data = response.data || "Request failed";
    console.log("Error reading", $scope.url, ".");
  });
    // scope parameter data is not accessible here, as it's not yet added
    //$scope.cardData = angular.fromJson($scope.data[0]);
    //console.log($scope.cardData);

}]);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download