user3107804 user3107804 - 2 months ago 7
Ajax Question

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":"a@gmail.com"},{"id":"2","name":"pratyush","email":"p@gmail.com"},{"id":"3","name":"ankit","email":"a@gmail.com"},{"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"}]

Answer

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;
});