0

I am using a static json file to simulate my server and getting my array of orders from it. I'm presenting the orders in a table in my html file with the option of deleting one from it. Each time I load the html file the full list gets loaded, with the orders I have deleted throught the controller function.

How can I loat the data from the factory only once?

Here is my controller:

app.controller("MainPageCtrl", function($scope, getOrdersFactory)
{
    $scope.orders = [];
    // Getting the data frm the facrory
    var dataPromise = getOrdersFactory.getDataFunc();
    dataPromise.then(function(data){
            $scope.orders = data.orders;
    });

    // Deletes an orders.
    $scope.deleteOrder = function(order){
    // Finds the index of the order.
    var orderIndex = $scope.orders.indexOf(order);

    // Delete the order.
    $scope.orders.splice(orderIndex, 1);
    };
});
2
  • What exactly do you mean? Once in a ... what? Do you want to store some data in browser cache? Commented Jul 26, 2016 at 8:32
  • See stackoverflow.com/questions/22182730/…. Commented Jul 26, 2016 at 8:34

2 Answers 2

0

By default angular services and factories are singletons(loaded only once). The problem you are facing is with controller re-initialization. When route change happens the controller is re-initialized so therby getting the previous value from the factory.

You can use a setter function on your 'getOrdersFactory'.

Assuming your 'getOrdersFactory' to be

app.factory('getOrdersFactory',function(){
 //code to read from file and set the file on a variable orderDetails
 var orderDetails = contentsReadFromFile;  
 return{
  getDataFunc:function(){
   return orderDetails
  },
  setDataFunc:function(modifiedOrderDetails){
   orderDetails = modifiedOrderDetails;
   //code to set the new content to the static file
  }
 }
}

code to read the file from the static file will be rendered when you inject the factory for the first time, and on your controller set the order details on the delete function

// Deletes an orders.
$scope.deleteOrder = function(order){
// Finds the index of the order.
var orderIndex = $scope.orders.indexOf(order);

// Delete the order.
$scope.orders.splice(orderIndex, 1);
getOrdersFactory.setDataFunc($scope.orders);
};
Sign up to request clarification or add additional context in comments.

Comments

0

I guess you are losing your data i.e $scope.orders .If this is the scenario just change

  dataPromise.then(function(data){
            $scope.orders = data.orders;
    });

to

  dataPromise.then(function(data){
            $scope.orders = angular.copy(data.orders);
    });

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.