我有一个使用工厂/服务的ionic1应用程序。
.factory('expenses', function($http) {
var expenseCategories = [];
return {
getCategories: function(){
return expenseCategories;
},
updateCategories: function(){
return $http.get('URL_HERE').then(function(response){
return expenseCategories = response.data.data[0];
});
},
storeCategory: function(category){
$http({
method: 'POST',
data: category,
url: 'URL_HERE',
headers: {
'Authorization': 'Bearer ' + localStorage.getItem("token")}
}).success(function(data) {
expenseCategories = data.data[0];
}).error(function(error){
});
}
}
})
在我的控制器中,我在页面加载时调用服务以显示类别,如果在服务中找不到类别,则它会检查API并更新服务中的类别。
if(expenses.getCategories().length != 0){
$scope.data.expenses = expenses.getCategories();
} else {
$scope.data.expenses = expenses.updateCategories();
};
更新后,用户可能想要添加其他类别。提交到我的API后,控制器再次调用getCategories()函数,但这不会更新DOM中当前的类别。我必须刷新页面才能获得最新的类别?
$scope.storeCategory = function()
{
expenses.storeCategory($scope.form);
$scope.data.expenses = expenses.getCategories();
$scope.closeModal();
}
供参考,这是我的整个控制器
.controller('expenseCategoryCtrl', function($scope, $state, expenses, $ionicModal, $http) {
$scope.data = {};
$scope.form = {};
if(expenses.getCategories().length != 0){
$scope.data.expenses = expenses.getCategories();
} else {
$scope.data.expenses = expenses.updateCategories();
};
$scope.storeCategory = function()
{
expenses.storeCategory($scope.form);
$scope.data.expenses = expenses.getCategories();
$scope.closeModal();
}
});
有人能指出我正确的方向吗?
答案 0 :(得分:1)
$scope.storeCategory = function()
{
expenses.storeCategory($scope.form);
$scope.data.expenses = expenses.getCategories();
$scope.closeModal();
}
更改为
$scope.storeCategory = function()
{
expenses.storeCategory($scope.form).then(function(data){
$scope.data.expenses = expenses.getCategories();
$scope.closeModal();
});
};
storeCategory必须是一个承诺,重新加载类别信息的逻辑必须是那些承诺成功的时候,希望有所帮助。