Richa Sharma
Richa Sharma

Reputation: 3

Ajax call in a function in controller

I am new to AngularJS.

I need to use a controller with a function called save, and make an ajax call inside the function.

My code looks like this now.

var app = angular.module("myApp1", []);

app.controller("AddController", ['$scope',$http {
    $scope.Save = function () {

    }
}])

I dont know how to proceed further.

Upvotes: 0

Views: 4406

Answers (2)

Manoj Ojha
Manoj Ojha

Reputation: 371

Hers is the solution

 var app = angular.module("myApp1", []);

app.controller("AddController", ['$scope','$http',function($scope,$http){`
      $scope.Save = function () {
        $http({
            method : "POST",
            url : "url",
            headers: { 'Content-Type': undefined },
            data:data
        }).then(function mySucces(response) {
            console.log(response.data);
        }, function myError(error) {
            console.log(error);
        });

    }}]);

where data will be json data object that you have to save.

Upvotes: 4

cornelius7
cornelius7

Reputation: 103

Something like this:

var app = angular.module("myApp1", []);

app.controller("AddController", ['$scope','$http',function($scope, $http) {
    $scope.Save = function () {
        $http.post(url, 
        {
            //data here
        }).then(function successCallback(response) {
            //success
        }, function errorCallback(response) {
            //error
        });
    }
}]);

Upvotes: 1

Related Questions