I am new to angular.js and I am trying to understand how to use the $http functions like $http.get and $http.post.
I have a very simple app retrieving messages from a MySQL database through a Java rest service. The data returned looks like:
[
{id:1, content:"Hello World!"},
{id:2, content:"Testing 1, 2, 3..."},
{id:3, content:"I am from the database"}
]
I am attempting to list them using ng-repeat like so:
<div ng-controller="MessageController">
<ul>
<li ng-repeat="m in messages">{{m.content}}</li>
</ul>
</div>
And then my controller looks like so:
function MessageController($scope, $http) {
$scope.getAll = function(callback) {
$http.get('/messages').success(function(response) { callback(response); });
}
$scope.messages = $scope.getAll(function(data) { return JSON.stringify(data); });
}
I see the call is properly returning an array of message objects and I can print them to the console from within the callback function but for some reason they are not being displayed in the ng-repeat. I was able to get this to work when I was manually creating a list of messages, but when I introduced the $http.get piece, it stopped working.
Am I missing something?
EDIT: I am using angular.js version 1.2.19
console.log-ing the response? Usually your data is on thedataproperty of theresponseobject in the$httpcallback. Try changingcallback(response)tocallback(response.data)...console.log(response); callback(response);...and the JSON array I mentioned above is printed. When I triedresponse.datait printedundefined.$scope.getAlldoesn't actually return anything. You can either have that $scope method update $scope.messages itself or you can make$scope.getAllreturn$http.getand then inside of the success callback returncallback(response). That way your$scope.getAllmethod returns a promise that will resolve with your evaluated callback. I believe that works.$resourcealso works but I abhor that service.