Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass data from factory to controller in angular js?

I have one factory contains save customer function.On success I want to pass its response in controller so that i can update the view.

Factory

sampleApp.factory("authFactory", function($location, $http, transformRequestAsFormPost) {
return {
    saveCustomer: function(data) {
        var request = $http({
            method: "post",
            url: "webservice/ws.php?mode=saveCustomer",
            transformRequest: transformRequestAsFormPost,
            data: data
        });
        request.success(
            function(response) {
            console.log(response);
            }
        );
      }
   };
}); 

Controller

sampleApp.controller('customerController', function($scope, testService,authFactory,$http) {
$scope.addCustomer = function() {
    var data = {name: $scope.customerName,city: $scope.customerCity};
    // Calling Factory Function
    authFactory.saveCustomer(data);
    // How to fetch response here       
   }
});

Please help me to solve that problem Thanks

like image 231
Varun Nayyar Avatar asked Dec 12 '25 13:12

Varun Nayyar


1 Answers

Various ways, the first one that comes to mind is something like this:

//in your factory
return {
   saveCustomer: function(data) {
       var request = $http({...});

       return request;
   }
}

//in your controller
authFactor
  .saveCustomer(data)
  .success(function() {
    //update controller here
  })
like image 106
Adam Avatar answered Dec 14 '25 03:12

Adam