这是我的控制器。
sampleApp.controller('SupplierController', ['$scope', '$http', 'SupplierService', function ($scope, $http, SupplierService){
$scope.Suppliers = [];
$scope.getSuppliers = function() {
SupplierService.getSuppliers().then(function(data) {
$scope.Suppliers = data;
});
};
$scope.editSupplier = function(supplier) {
SupplierService.editSupplier(supplier);
editMode = false;
};
$scope.getSuppliers();
}]);
这是我的服务。
sampleApp.factory('SupplierService', function($http, $q) {
var SupplierService = {};
var SupplierList = [];
SupplierService.getSuppliers = function() {
var Info = {};
Info.Action = "GET";
Info = JSON.stringify (Info);
var req = {
url: SupplierURL,
method: 'POST',
headers: { 'Content-Type': 'application/json'},
data: Info
};
if ( SupplierList.length === 0 )
{
return $http(req).then(function (response) {
SupplierList = response.data
return response.data;
});
}
else
{
var deferred = $q.defer();
deferred.resolve(SupplierList);
return deferred.promise;
}
};
SupplierService.addNewSupplier = function(supplier) {
var Info = {};
Info.Action = "ADD";
Info.SupplierName = supplier.name;
Info.SupplierMobile = supplier.mobile;
Info = JSON.stringify (Info);
var req = {
url: SupplierURL,
method: 'POST',
headers: { 'Content-Type': 'application/json'},
data: Info
};
$http(req)
.success(function(data) {
alert ('Supplier update is successful.');
})
.error(function (data, status, headers, config) {
alert ('Supplier update error.');
});
};
SupplierService.editSupplier = function(supplier) {
var Info = {};
Info.Action = "UPDATE";
Info.SupplierID = supplier.id;
Info.SupplierName = supplier.name;
Info.SupplierMobile = supplier.mobile;
Info = JSON.stringify (Info);
var req = {
url: SupplierURL,
method: 'POST',
headers: { 'Content-Type': 'application/json'},
data: Info
};
$http(req)
.success(function(data) {
alert ('Supplier update is successful.');
})
.error(function (data, status, headers, config) {
alert ('Supplier update error.');
});
};
return SupplierService;
});
我想要的是,只有当editSupplier的http调用成功时,才会执行此行。
editMode = false;
目前上面的行是$ scope.editSupplier函数。所以无论成功与否,它都会被称为。如何将此行移至服务区?
任何更好的方法都将受到高度赞赏。
答案 0 :(得分:3)
根据您当前的设置,最简单的方法是返回$http(req)
(因为这是一个承诺)。所以editSupplier
的结尾会说:
return $http(req);
在你的控制器中,你可以这样做:
SupplierService.editSupplier(supplier).success(function(response) {
editMode = false;
});
如果您在发生错误时有特定的事情,可以另外链接.error
处理程序。
答案 1 :(得分:1)
@tandrewnichols偷走了我的初步答案,所以我会提供替代方案。:p
将editMode移动到服务中并使用getter检查editMode的值。 另外,您打算在您的应用程序中使editMode成为全局变量吗?