3

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

2 Answers 2

4

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

Comments

3

You are working with "promises" here. You can do a few different things depending on what you return from your service method.

One thing you can do is simply return the promise and handle it in your controller.

service:

return {
    saveCustomer: function(data) {
        return $http({...});
   }
}

contoller:

authFactor.saveCustomer(data).success(function(customer) {
    $scope.customer = customer;
})

Another thing you can do is return an object reference and put it on your scope. When the object is filled, it will be updated in your scope.

service:

return {
   saveCustomer: function(data) {
       var customer = {};
       $http({...}).success(function(data){
           angular.copy(data, customer);
       });
       return customer;
   }
}

controller:

$scope.customer = authFactor.saveCustomer(data);

The advantage of this second way is that most of your logic stays in your service. You controller stays simple and doesn't have to know about promises or handle them.

1 Comment

thanks for your reply.. I am trying to use your second approach as mentioned in your answer but it is not working.

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.