0

I am new to angular js, I am using local storage in my project. I want to store the data in local storage dynamically.

What is the best way to achieve this?

My function is :

$scope.saveItem=function(){
    var dataobj= {  'itemCode':vm.person1.selected.itemCode,
                    'itemName':'name',
                    'qty':'1',
                    'price':'2',
                    'total':1 * 2,
                    'comment':'comment',
                   };
    localStorageService.set('order',dataobj);
}

I have entered the static data here but this data will be dynamic when I add the new item and I want to keep previous data and store newly entered data in local storage.

2 Answers 2

1

I don't know why using a service for localStorage, you can simply use localStorage native API. When you add some item just do something like this :

var order = localStorage.getItem('order');
if(order) {
   localStorage.setItem('previousOrder', order);
}
localStorage.setItem('order', NEW_ORDER_DATA_HERE);

NOTE : A storage item must be a DOMString so think about JSON.stringify and JSON.parse your data before storing and fetching them.

Sign up to request clarification or add additional context in comments.

Comments

1

I used this code , it works prefectly :

    $scope.temp=JSON.parse(localStorage.getItem(vm.person.selected.cust_id));
    if($scope.temp){
    $scope.order = $scope.temp;
    }else{
    $scope.order=[];
    }   
    localStorage.setItem(vm.person.selected.cust_id, JSON.stringify($scope.order));

    var dataobj={'itemCode':vm.person1.selected.itemCode,
         'itemName':vm.person1.selected.itemName,
         'qty':vm.qty,
         'price':vm.price,
         'total':vm.qty * vm.price,
         'comment':vm.comment,
         'orderType':$scope.heading
         };
    $scope.order.unshift(dataobj);           
    localStorage.setItem(vm.person.selected.cust_id,JSON.stringify($scope.order));
    $scope.allCurrentTakeAwayOrder=$scope.order;

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.