duanjie6912
duanjie6912
2017-07-20 21:03

Ionic1工厂更新并返回更改

已采纳

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?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

1条回答

  • dsf6565 dsf6565 4年前
    $scope.storeCategory = function()
      {
    
        expenses.storeCategory($scope.form);
        $scope.data.expenses = expenses.getCategories();
        $scope.closeModal();
    
      }
    

    change to

    $scope.storeCategory = function()
      {
    
        expenses.storeCategory($scope.form).then(function(data){
            $scope.data.expenses = expenses.getCategories();
            $scope.closeModal();
        });
      };
    

    The storeCategory must be a promise, and the logic to reload the infor of categories must be when success those promise, hope helps.

    点赞 评论 复制链接分享

为你推荐