[英]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. 我有一个工厂包含保存客户功能 。成功我想在控制器中传递其响应,以便我可以更新视图。
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);
}
);
}
};
});
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 请帮我解决这个问题谢谢
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
})
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. 你的控制器保持简单,不必知道承诺或处理它们。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.