Pratyush Pranjal
Pratyush Pranjal

Reputation: 554

Angular Js ng-repeat can't getting output from json array using ajax

I am using Angular Js having ajax but by using ng-repeat can't getting output from json array. On alert getting [Object object]...so on but by using $scope.names= response[0].id; , getting "1" id on alert. I need to get all data in table. Is there any way to get all data in table and also I am not using $http in controller because it not working in mobile browser but works in desktop, i don't know why?Please help!

JS

var app = angular.module('studentApp',[]);
app.controller('StudentCntrl', function($scope){

$.ajax({
    url : '/fetchAllData',
    type : 'GET',
    success : function(response){
        $scope.names=response;
        //alert($scope.names);(This is working)
          } 
     });
});

JSP

<div ng-app="studentApp" ng-controller="StudentCntrl">

      <div class="table-responsive">
        <table class="table table-striped">
          <thead>
            <tr>
              <th>ID</th>
              <th>NAME</th>
              <th>EMAIL</th>
            </tr>
          </thead>
          <tbody>
            <tr ng-repeat="x in names">
              <td>{{x.id}}</td>
              <td>{{x.name}}</td>
              <td>{{x.email}}</td>

            </tr>
          </tbody>
        </table>
      </div>

Json

[{"id":"1","name":"abdul","email":"[email protected]"},{"id":"2","name":"pratyush","email":"[email protected]"},{"id":"3","name":"ankit","email":"[email protected]"},{"id":"45","name":"kjhj","email":"kjhkj"},{"id":null,"name":null,"email":null},{"id":null,"name":null,"email":null},{"id":null,"name":null,"email":null},{"id":"trffs","name":null,"email":null},{"id":"afa","name":"sdgfdsg","email":"dsagdsg"},{"id":"12","name":"pppp","email":"hjk,gh"}]

Upvotes: 2

Views: 245

Answers (2)

Robbert Helling
Robbert Helling

Reputation: 36

When updating the scope with an $ajax call (you should use $http), you have to use $scope apply to update your bindings.

$scope.$apply(function(){
    $scope.names = response.data;
});

Upvotes: 1

Sajeetharan
Sajeetharan

Reputation: 222582

Instead of ajax call , use $http with angular as below

var app = angular.module('studentApp', []);
app.controller('StudentCntrl', function($scope,$http) {
    $http.get('data.json').then(function (response){
                  console.log(response.data.pages);
                $scope.names = response.data;
        });
});

Here is the working DEMO

Upvotes: 1

Related Questions