1

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?

1 Answer 1

3

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>
Sign up to request clarification or add additional context in comments.

3 Comments

So if I want to append another element I should already create it but just not show it and when I want to show it change the ng-show to true? And my AJAX call are done ok? cause they look kinda messy
If you want to add elements to DOM conditionally then you can use ng-if directive available in v1.1.5.
I get the sense that as an Angular best practice you should keep your Logic in the Controller, and DOM manipulation in Directives leaning on ng-if only when you need to.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.