Reputation: 2322
I'm a little confused how to implement the callback from a successful AJAX call to my RESTful server. This is how I fetch the data:
Service:
app.factory('Data', function($http) {
var factory = {};
factory.get = function(id, success, error) {
$http.post("/api/"+id).success(success);
return factory
};
I prefer having self defined functions (e.g. factory.get()) to use in my controller.
Controller:
app.controller('Ctrl', function($scope, Data) {
var onSuccess = function(data, status) {
// I want to append something to the DOM here
}
};
$scope.get = function(id) {
Data.get(id, onSuccess)
};
});
Here I'm defining a get function I can use in my HTML and I have to pass in an id. However, I have no idea how to access the element so I can append the information from the JSON response to the DOM in the onSuccess function.
Do I have to create a directive to accomplish this? Is this a right way to make AJAX calls?
Upvotes: 1
Views: 9214
Reputation: 43947
For the server response to be accessible inside the DOM, it needs to be in the scope of your controller. You can do this by assigning the returned data to a $scope variable inside the success callback:
app.controller('Ctrl', function($scope, Data) {
$scope.get = function(id) {
Data.get(id).success(function(data, status) {
$scope.status = status;
$scope.data = data;
});
};
});
Now you can simply refer to $scope.data
as data
inside the HTML:
<div ng-repeat="item in data">
{{item}}
</div>
Upvotes: 3