I have an ionic1 application which uses a factory / service.
.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){
});
}
}
})
In my controller I'm calling the service on page load to show the categories, if no categories are found in the service it then checks the API and updates the categories in the service.
if(expenses.getCategories().length != 0){
$scope.data.expenses = expenses.getCategories();
} else {
$scope.data.expenses = expenses.updateCategories();
};
After updating, the user may want to add another category. After submitting to my API the controller calls the getCategories() function again but this isn't updating the categories currently in the DOM. I have to refresh the page to get the latest categories?
$scope.storeCategory = function()
{
expenses.storeCategory($scope.form);
$scope.data.expenses = expenses.getCategories();
$scope.closeModal();
}
for reference here's my entire controller
.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();
}
});
Can anyone point me in the right direction?