1

I'm not sure why when i print the json file on a html page works, also from a button calling a function, but not inside of the javascript file.

This a problem because i need to sort the data in the json file before displaying it from in the web page, i can't make it work. i tried using this solution https://stackoverflow.com/a/15463124/2796268, but the console say

jsonDat is not defined

my code:

$scope.init = function () {

        console.log("init");
    $http.get('json/file.json') .success(function(data) {
           $scope.jsonDat = res.data; 
        })
        .error(function(data,status,error,config){
            $scope.jsonDat = [{heading:"Error",description:"Could not load json   data"}];
        });

     console.log(jsonDat);

};

How i can process the json data before the page loads or when the page is loading?

Community
  • 1
  • 1
Progs
  • 1,059
  • 7
  • 27
  • 63
  • looks like you want $scope.jsonDat, not jsonDat. Keep in mind you'll have access to it inside the success callback guaranteed, but everywhere else it must be treated as an asynchronous variable (it could be null or it could be resolved data) – Hypaethral Oct 15 '15 at 17:28
  • @GrumbleSnatch ok, it kinda works now, but it prints an empty array – Progs Oct 15 '15 at 17:33

3 Answers3

3

You can process the data when it is returned from $http, like so:

$scope.init = function () {
    $http.get('json/file.json').success(function(data) {
        //---- SORT HERE ----
        $scope.jsonDat =  mySortFunction(data);
    });
};
Miles P
  • 710
  • 4
  • 12
2

Try this :

$scope.init = function() {

    console.log("init");
    $http.get('json/file.json').success(function(data) {
            $scope.jsonDat = data;
            console.log($scope.jsonDat);
        })
        .error(function(data, status, error, config) {
            $scope.jsonDat = [{
                heading: "Error",
                description: "Could not load json   data"
            }];
            console.log($scope.jsonDat);
        });

};

In success you have data but you try get from res.data. When you use success then it is not response with data but only your data.

Bartosz Czerwonka
  • 1,631
  • 1
  • 10
  • 11
1

I thought you wanna sort some JSON file then display it in HTML page . So My Idea is get that JSON file (you tried)

$http.get('json/file.json') .success(function(data) {
       $scope.jsonDat = data.res; 
       console.log('Checking the result',angular.toJson($scope.jsonDat));
    })

But putting your result in

$scope.jsonDat = data.res; 

eg,

sortService.sortJsn = data.res;

$scope.jsonDat instead create angular service pour your data there then you can access those data any where in your controller sort it also show it in HTML.

SakthiSureshAnand
  • 1,324
  • 16
  • 32