Mahesh Gadagi Mahesh Gadagi - 2 months ago 21
AngularJS Question

AngularJS JSON load from file with ng-click

Currently I want to show HTML table by parsing JSON data from file using Angular JS, And It's not working can someone please help me?

And Also As a Enhancement How Can I get the 2 Divs for 2 different JSON file

HTML Code

<html>
<div ng-controller="get_controller">
<input type="text" ng-model="accountnumber" name="accountnumber" class="form-control search-query" placeholder="Enter Account Number">
<span class="input-group-btn">
<button type="submit" ng-click="geValues()" class="btn btn-primary">Submit</button>
</span>
</div>

<div ng-controller="get_controller">
<table>
<tbody>
<tr>
<th ng-repeat="list in personDetails">{{list.Name}}
</th>
</tr>
<tr>
<td class="features" ng-repeat="list in personDetails">{{list.Location}}
</td>
</tr>
</tbody>
</table>
</div>
</html>


Angular JS Code

var app = angular.module('myApp', ["ngTable"]);
app.controller('get_controller', function ($scope, $http) {

$scope.geValues = function() {
$http({method: 'POST', url: 'posts.json'}).success(function(data) {
$scope.post = data;
$scope.personDetails = Employee;
})
},
});


posts.json (Json File)

{
"Employee": [
{
"Name": "Rocky",
"Location": "Office"
},
{
"Name": "John",
"Location": "Home"
}
]
}

Answer

Should be a GET request, also the you need to access the data from the response object which contains the Employee array. Code should be,

$http.get('test.json').then(function (response){
  $scope.post = response.data;
  $scope.personDetails = response.data.Employee;
});

if you want it to happen on ng-click, put the call inside a function,

  $scope.geValues = function() {
      $http.get('test.json').then(function(response) {
        $scope.post = response.data;
        $scope.personDetails = response.data.Employee;

      });
    }

DEMO

Comments