Reputation: 309
I am new to this and i am trying to make a dummy contact list. I have printed the log which fetches the data from mongodb and i can see the correct data in browser console,but when i try to print it in html file it doesn't display.
Here are the snippets:
controller.js
var myApp = angular.module('myApp', []);
myApp.controller('AppCtrl', ['$scope', '$http', function($scope, $http){
$http.get('/contactlist').then(function(response){
console.log("I got the response");
console.log(response); //able to see correct data is fetched in the browser console
$scope.contactlist=response;
});
}])
Table where i try to print this data:
<tbody>
<tr ng-repeat="Contact in contactlist">
<td>{{Contact.name}}</td>
<td>{{Contact.email}}</td>
<td>{{Contact.number}}</td>
</tr>
</tbody>
Please explain what is going wrong.
Upvotes: 0
Views: 240
Reputation: 1777
JavaScript is always synchronous. So what is happening here, $scope.contactlist=response;
is executing before $http.get('/contactlist')...
completed. It means, $scope.contactlist
undefined. To Solve this problem,
I recommend to use Service
.
var myApp = angular.module('myApp', []);
myApp.controller('AppCtrl', ['$scope', 'dataService', function($scope, dataService){
dataService.contactLists(function(response) {
console.log(response.data);
$scope.contactlist=response.data;
});
});
}])
myApp.service('dataService', function($http) {
this.contactLists = function(callback){
$http.get('/contactlist').then(callback)
}
});
Upvotes: 1