12

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.

Community
  • 1
  • 1
Divyanth Jayaraj
  • 950
  • 4
  • 12
  • 29
  • 2
    try removing the trailing comma. make sure the JSON validates @ jsonlint.com – charlietfl Jun 01 '14 at 22:02
  • For security purposes, most browsers will prevent AJAX requests to the filesystem, which could cause this error... are you running your code on a local server, or just opening your HTML file directly in your browser? You'll need to setup a simple server if you haven't already. – Hylianpuffball Jun 02 '14 at 01:00

5 Answers5

6

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

Prasad
  • 1,562
  • 5
  • 26
  • 40
5

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.

mmm
  • 2,272
  • 3
  • 25
  • 41
  • 1
    Sorry, that's not working. I'm sure my problem is exactly the same as in this tutorial https://docs.angularjs.org/tutorial/step_05. Still doesn't work. – Divyanth Jayaraj Jun 02 '14 at 03:52
  • 1
    @emilySmitley Dude the Above Concept You Explained Damn Good .. I have been Wondering Why It is Not Saving data. "Thanks A LOT You ". "Thanks A LOT You " :-) – Prasad Apr 30 '15 at 08:47
  • Dude Do you have any idea about time Subtractions with Momentjs ? – Prasad May 01 '15 at 19:56
  • You should ask that as a stack overflow question @PRASAD – mmm May 02 '15 at 17:24
2
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.

Jace Rhea
  • 4,982
  • 4
  • 36
  • 55
  • When You Injected $http service Use '$http.get' which is Straight and Easy . I Answered Take a Look and Let me Know your Questions – Prasad Apr 30 '15 at 09:30
0

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"}
 ]
}
ONE_FE
  • 968
  • 3
  • 19
  • 39
0

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"}];
    });
LIQvID
  • 147
  • 1
  • 10