Divyanth Jayaraj
Divyanth Jayaraj

Reputation: 960

AngularJS: How to load JSON data onto a scope variable

I'm creating a personal website where I can keep updating content without having to manipulate the HTML. I'm trying to achieve this by simply loading and updating a JSON file. But right now, I'm having trouble loading JSON data onto a scope variable.

HTML

<!doctype html>

<html>
    <head>
        <script src="angular.min.js" type="text/javascript"></script>
        <script src="maincontroller.js" type="text/javascript"></script>
    </head>
    <body>
        <div ng-app="mainApp" ng-controller="mainController">
            <div id="content">
                <div ng-repeat="content in contents">
                    <h2>{{content.heading}}</h2>
                    <p>{{content.description}}</h2>
                </div>
            </div>
        </div>
    </body>
</html>

maincontroller.js

var myapp = angular.module('mainApp', []);
myapp.controller('mainController',function($scope,$http){

    $scope.contents = null;
    $http.get('mainContent.json')
        .success(function(data) {
            $scope.contents=data;
        })
        .error(function(data,status,error,config){
            $scope.contents = [{heading:"Error",description:"Could not load json   data"}];
        });

    //$scope.contents = [{heading:"Content heading", description:"The actual content"}];
    //Just a placeholder. All web content will be in this format
});

This is what the JSON file looks like

[
    {"heading":"MyHeading","description":"myDescription"},
]

I actually tried following the solution given here, but it's not loading the JSON file stored in the same folder. The output I get is from the error handling function which is saying Error: Cannot load JSON data as mentioned.

What am I doing wrong?

EDIT: I put the same code on plunker and it works fine. It's just not working on my local machine.

Upvotes: 12

Views: 76240

Answers (5)

Prasad
Prasad

Reputation: 1600

Modified Your Method Use this and Check output.

var myapp=angular.module('mainApp',[]);
myapp.controller('mainController',function($scope,$http){
    $scope.content = null;
    $http.get('urlpath'}).
        success(function(data, status, headers, config) {
            $scope.contents=data;
        }).error(function(data, status, headers, config) {          
    });
});

or Another Good Practice I see

Use Factory Service Method:-

angular.module('mainApp').factory('Myservice', function($http){
    return {
        getdata: function(){
              return $http.get('url'); // You Have to give Correct Url either Local path or api etc 
           
        }
    };
});

Inject above service to Controller

Controller :-

angular.module('mainApp',[]).controller('mainController',function($scope,Myservice){
        $scope.content = null;
         Myservice.getdata().success(function (data){
           alert('Success');
           $scope.content=data[0]; // as per  emilySmitley Answer which is Working Good
         });
      });

Let Me Know if You have any Questions. Good Luck

Upvotes: 6

LIQvID
LIQvID

Reputation: 157

I don't know if you have still been able out the solution or not. If not, do try this. When using localhost server, the server is unable to locate the json files. To solve this problem, just rename your file to mainContent.txt, apart from that, your code is perfect. But do remember that this is only for development phase, once you plan to deploy the site live, change back to .json file.

updated $http request :-

$scope.contents = null;
$http.get('mainContent.json')
    .success(function(data) {
        $scope.contents=data;
    })
    .error(function(data,status,error,config){
        $scope.contents = [{heading:"Error",description:"Could not load json   data"}];
    });

Upvotes: 0

ONE_FE
ONE_FE

Reputation: 996

Change your mainController.js and JSON files as follows. Here i'm using wamp server as my local server.

var myapp = angular.module('mainApp', []);
myapp.controller('mainController', function($scope, $http) {
  $http.get('http://localhost/stackoverflow/angular/test1/database.json').success (function(data) {
    $scope.contents = data.records;
  })
});

JSON File:

{
 "records":
 [
    {"heading":"MyHeading","description":"myDescription"}
 ]
}

Upvotes: 0

mmm
mmm

Reputation: 2297

Your json file has an array with the first and only element in the array being a json object. When .success() fires, and data is passed into the lambda function, data is an array, not just json. All you have to do is access the zeroth element of the array.

So this:

.success(function(data) {
    $scope.contents = data;
})

Should be this:

.success(function(data) {
    $scope.contents = data[0];
})

Also, you should check data[0] to make sure that it's json, and if it doesn't validate, you should probably call parseJSON(data[0]) on it.

Upvotes: 5

Vanitha kumari
Vanitha kumari

Reputation: 21

var myapp=angular.module('mainApp',[]);
myapp.controller('mainController',function($scope,$http){
    $scope.content = null;
    $http({method: 'GET', url: 'mainContent.json'}).
        success(function(data, status, headers, config) {
            $scope.contents=data;
        }).error(function(data, status, headers, config) {          
    });
});

Published in Web Server and added Mime type for .json. It worked.

Upvotes: 2

Related Questions