繁体   English   中英

如何在角度js中将数据从工厂传递到控制器?

[英]How to pass data from factory to controller in angular js?

我有一个工厂包含保存客户功能 。成功我想在控制器中传递其响应,以便我可以更新视图。

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       
   }
});

请帮我解决这个问题谢谢

各种方式,首先想到的是这样的:

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

       return request;
   }
}

//in your controller
authFactor
  .saveCustomer(data)
  .success(function() {
    //update controller here
  })

你在这里工作“ 承诺 ”。 根据您从服务方法返回的内容,您可以执行一些不同的操作。

您可以做的一件事就是返回承诺并在控制器中处理它。

服务:

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

位指示:

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

您可以做的另一件事是返回一个对象引用并将其放在您的范围上。 填充对象后,它将在您的范围内更新。

服务:

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

控制器:

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

第二种方式的优点是大多数逻辑都保留在您的服务中。 你的控制器保持简单,不必知道承诺或处理它们。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM