hanu
hanu

Reputation: 397

how to read data from json file in angular js

I created a json file under json folder json/caseNames.json and trying to read that file in a controller. Here is my code. When I debug this code it is not going to the next statement after $http.get line. How do I read the file? Does it have any syntax errors?

app.controller('CaseNamesController',function($http,$scope){
    $scope.names = [];

  $http.get('/json/caseNames.json')
    .success(function(response){
        console.log(response);
        $scope.names = response;
    })
    .error(function(response){
        $scope.names =[];
  });

});

Upvotes: 0

Views: 80

Answers (2)

Vinay
Vinay

Reputation: 1034

Add a ".." so that it can navigate to the json folder. I ran it using another JSON file and I was able to output the data on the console.

app.controller('CaseNamesController',function($http,$scope){ 

    $scope.names = [];

  $http.get("../json/caseNames.json")
    .success(function(response){
        console.log(response);
        $scope.names = response;
    })
    .error(function(response){
        $scope.names =[];
  });

});

Upvotes: 0

taxicala
taxicala

Reputation: 21759

success and error both are now deprecated, you should use then instead which receives the success handler as the first parameter, and the error handler as the second:

app.controller('CaseNamesController',function($http,$scope){
    $scope.names = [];
    $http.get('/json/caseNames.json').then(
        function(response){
            console.log(response);
            $scope.names = response;
        }, 
        function(response){
            $scope.names =[];
        }
    );
});

Upvotes: 1

Related Questions