Use ngStorage For All Your AngularJS Local Storage Needs

I’ve been doing a lot of work with AngularJS lately, and in particular Ionic Framework.  However, up until recently I have been using either HTML5 local storage or SQLite.

Now I’ve switched gears and started using the AngularJS module ngStorage which has made my life a lot easier.

Previously when using HTML5 local storage, I continuously had to serialize and unserialize my objects before using or saving them.  For example, let’s say I had the following object:

If I wanted to save this object into local storage I would have had to serialize it using the JSON.stringify function.

The above code will save our object under the key saved in local storage.

If we wanted to use the object that we saved we would have to unserialize it using the JSON.parse function.

Alright, so you’re probably wondering by now what makes ngStorage different.

ngStorage via GitHub repository:

Right from AngularJS homepage: “Unlike other frameworks, there is no need to […] wrap the model in accessors methods. Just plain old JavaScript here.” Now you can enjoy the same benefit while achieving data persistence with Web Storage.

You can save and use your objects in object form.  No need to serialize or unserialize your data.

So lets get a sample AngularJS project started to demonstrate how to use the ngStorage library.

The above code is just a very basic example page that demonstrates how to use ngStorage in your project.  Notice the two highlighted lines.  This is how you include the library in your project for use.

With the library set up and ready to go, you can use it like any other JavaScript object.  Keeps your code clean with minimal headache.

A video version of this article can be seen below.

Nic Raboy

Nic Raboy is an advocate of modern web and mobile development technologies. He has experience in Java, JavaScript, Golang and a variety of frameworks such as Angular, NativeScript, and Apache Cordova. Nic writes about his development experiences related to making web and mobile development easier to understand.

  • studiorooster

    Rockin…you have to love Angular. Thanks for the tut; I will definitley find use for this one.

  • loic knuchel

    Really good lib but quite dangerous on mobile if you work with large objects (like cache). Any small change in model with trigger a serialization and can cause performance problems in mobile. Now, I’m using https://github.com/ocombe/angular-localForage 🙂

    • Thanks for sharing 🙂

      For many app developers, they probably won’t be requiring massive amounts of storage. There are always different options for different scenarios.

      Regards,

  • One quick question,

    If I use $localstorage.username = “someusername”; in my controller firstCtrl, let say

    Then willI I be able to use

    $scope.username = $localstorage.username

    at some other controller?

    If yes, I will download it right away.

    • Hi,

      You are correct. Anything in the $localstorage object can be used throughout your application regardless of controller or function.

      Regards,

      • Awesome,

        as of now, I was making call to my php page on server to get user id, and I know thats was pathetic.

        Thank you so much (y)

        & also I was wondering if you could help me with image upload to server?

      • Hi Nic,

        Good Day Again,

        Well for some reason I am getting an issue with $localStorage

        I have stored Facebook ID at my controller ProcessCtrl

        and then states moves to Feed page handled by FeedCtrl

        When I console.log($localStorage.fbid);

        It returns undefined.

        I have passed $localStorage in parameters of both controllers too.

        Anyidea?

        • Take a look at the following Facebook example that I had done for Ionic Framework:

          https://github.com/nraboy/ng-cordova-facebook-example

          It demonstrates usage of ngStorage and Facebook. If you’re unfamiliar with Apache Cordova / Ionic Framework, everything you’ll need is in the www directory of the project.

          Regards,

          • bharath

            same problem is occuring for me and 1st time data is not coming showing undefined but 2nd time it is coming .

          • That is strange. Maybe the listener hasn’t triggered yet before moving?

            https://github.com/gsklee/ngStorage/blob/master/ngStorage.js

            What if you set a $timeout after saving data?

            I personally have not run into this issue. Put your code on Gist if you want someone to take a look.

            Regards,

          • bharath

            login.html
            app.controller(“LoginController”, [“$scope”,”$rootScope”,”$location”,”$localStorage”,”$window”, “authenticationSvc”,function ($scope,$rootScope, $location,$localStorage, $window, authenticationSvc) {
            $scope.userInfo = null;
            $scope.login = function () {
            authenticationSvc.login($scope.loginName, $scope.password)
            .then(function (result) {
            $rootScope.userInfo = result;
            $localStorage.info=$rootScope.userInfo;
            $window.location.href = ‘../../view/admin/main.html’;
            }, function (error) {
            $window.alert(“Invalid credentials”);
            });
            };

            main.html

            app.controller(‘data’,[“$scope”,”$rootScope”,”$localStorage”,function ($scope,$rootScope,$localStorage) {
            $localStorage.newinfo=$localStorage.info;
            $scope.logindetails=$localStorage.newinfo;
            $rootScope.header=$scope.logindetails;

            }]);
            it is showing undefined first and 2nd or 3rd time values are coming ,we need to use ngCordova?

          • A few things:

            1. I had requested you add your code to Gist because the comments section of any blog is not an appropriate place to add code
            2. You have a lot of swapping between $localStorage, $scope and $rootScope. I don’t think that is a good way to do things and may be the reason for your jam up
            3. Maybe throw a $rootScope.$apply() in there to refresh those scopes after you set them?

            Regards,

          • bharath

            ok right now iam only one rootscope and if possible share one example in
            localstorage using one html file to another

          • I know this example is for Ionic Framework and not a web application, but it works fine.

            https://github.com/nraboy/ng-cordova-facebook-example

            Just look in the www directory.

            Regards,

          • bharath

            ok when i keeping the break point it is working but when i remove the break point it is not showing

          • What break point are you referring to?

          • bharath

            browser breakpoints

          • Have you tried $rootScope.$appy() after setting your $scope to $localStorage?

          • bharath

            I used but same error,if possible share your mailid i will send my code

          • Sorry, but I don’t share my email. If you want me to test your code you’re going to have to put it on GitHub.

          • bharath
          • bharath

            hv u check the code

          • bharath

            hi local storage is not working on ctrl+click i mean on new tab

          • I replied to your post on StackOverflow, even though GitHub was the preferred method.

            I believe it isn’t working because you’re not doing things the AngularJS way. The example code I posted in your StackOverflow question works fine and it makes use of the AngularJS UI-Router to navigate between page templates.

            Regards,

          • bharath

            hi local storage is not working on ctrl+click i mean on new tab

  • sudeep

    thats awesome post Thanks dude !!

    • No problem. Thanks for the compliment!

  • mark_ellul

    Hi, I just found your blog and love it! I am new to Angular and Ionic, and was looking at using SQLite until I found this post. How would I use ngStorage instead of or in complement with SQLite?

    • Hi Mark,

      Thanks for the compliment!

      I think the solution would be best chosen based on what you’re trying to accomplish. For example, maybe you want to keep SQLite for complex data relationships and use ngStorage for application settings or preferences. Or maybe you want to store the objects directly returned from RESTful APIs into the ngStorage.

      It all depends.

      Care to share what your end goal is?

      Regards,

      • mark_ellul

        My end goal is to store a list of items with media that the user inputs, and selectively returning that list of items locally on the phone. SQLite makes the most sense for this model. The aim would be later to allow a user to save their data to the “cloud” via Parse or similar.

        Regards

        • Hi Mark,

          I always find the relational model of SQL favorable, but in reality the model of local storage works too. However, I have played with Firebase and the Dropbox Datastore API, and can tell you local storage is a heck of a lot easier when working with cloud data storage.

          Just to confirm. You’re not trying to store actual media files in your database or local storage correct? Only references to them on the file system, yes? I can’t imagine it ending well if you’re trying to store them in a database.

          Regards,

          • mark_ellul

            Hi Nic,

            I won’t store the actual media in the database, they will be references to the local file system. But there will be text data and numerical data stored with the references.

            The aim would be allow the user to move/sync their data (including files) from mobile to another mobile. When they lose or upgrade their phones, but not as a real time option.

            Thanks for mentioning the Dropbox Datastore API, that seems like a perfect system to offload all the sync needs to them. https://www.dropbox.com/developers/blog/97/sync-api-and-datastore-api-30-beta-release looks like I could even go with them directly.

            Firebase looks good as well, https://www.firebase.com/docs/web/libraries/angular/ They might even go free considering they have joined Google.

            Thanks again for all your ideas and Regards

          • Hi Mark,

            Check out this post I did regarding the Dropbox Datastore API with Ionic Framework:

            https://www.thepolyglotdeveloper.com/2014/10/syncing-data-dropbox-using-ionicframework/

            I also have a queued post for the end of the month regarding Firebase. Subscribe to my blog with your email so you don’t miss it.

            Regards,

          • mark_ellul

            Hi Nic,

            Thanks, I already had your Dropbox Datastore API blog post open. I just subscribed by email to your blog, and am looking forward to the Firebase post. Do you know if Firebase offers file sync as well?

            I did notice that the Dropbox Datastore API does have some limits on data sizes, specifically 100,000 records with a max datastore size of 10MB. Though in the short term I don’t imagine that this would be a huge issue.

            Considering that I would probably need to sync files as well. So Dropbox (using the Phonegap plugins per platform, https://github.com/rossmartin/phonegap-dropbox-sync-android and https://github.com/ccoenraets/phonegap-dropbox-sync) may be my best option, especially if it allows a mobile app without needing 100% connectivity all the time.

            Thanks again for your comments

          • mark_ellul

            The Dropbox datastore API, means a non centralised data store right? i.e. each end user will have access to their data, and will need to sign up to dropbox if they want to “sync” their data and none of that data will be shared to me the developer right?

          • Since we’ve changed topics, please move these Dropbox questions to the other post I had made 🙂

  • cedric sandars

    Hi Nic,

    Great article… I have used other examples of yours in couple of my projects 🙂

    Now, I have seen web app’s or even reuters mobile application changes articles title color when someone views a particular article. Question here would be can we use ngStorage to accomplish the same functionality or do you have any other recommendation?

    Thanks!


    Cedric

    • Hi Cedric,

      I may not completely understand what you’re asking, but I’ll take a shot at it.

      You can set an indicator in ngStorage and then do a check via your application for such indicator. If value x do something, otherwise do something else.

      For example:


      Title
      Title

      Where indicator is $scope.indicator set in your controller using whatever is found in local storage.

      Does this help?

      Regards,

      • cedric sandars

        I think this is what I’m looking for. Let me try to play with the code and get back if I need any help.

        Thanks again Nic!!!

        • No problem! Let me know how it goes 🙂

  • Mike Brady

    Hi Nic,

    I have been using ngStorage to locally reflect a listing from a REST service which I am serving using mongo and mongoose. Can I dip in and change a single object parameter within the localStorage ‘collection’ in a similar way to mongo? I would like my users for instance to be looking at a list of items from localStorage, mark one as a favourite and and just change that one value within a single object e.g. fave: true. Is this possible with ngStorage?

    • Steve OConnor

      Hi Mike,

      If I can hijack the question and answer that one for you …. the answer is a big fat YES. Its even simpler than mongo, because you dont have to explicitly save the collection to the storage.

      Whatever JS objects you attach references to on the $localStorage object will get watched, and saved to local storage automatically, whenever angular does its little digest loop.

      So if you have a huge and complex set of data in
      var myBigComplexObject = { blah, blah, blah ….. }

      and stick this on the $localStorage object :
      $localStorage.myBigComplexObject = myBigComplexObject

      Then you are good to go.

      After having done this, lets say you have some code that does this horribly deep assignment of a single boolean value inside that structure :

      myBigComplexObject.TODOList[ $dayOfWeek ].bookOfTheDay.favorite = true

      … then that will update that value on the browser’s local storage (after a very short delay), without you needing to add any more code.

      Is that what you meant ?

      • Thanks for jumping in right before I hit “Post” 😉

        Good explanation Steve!

      • Mike Brady

        Well, yeah, I think so. But at the moment I’m creating a $scope.updateWhere() function.

        This function’s paramaters will:

        – Take in a search value from the ‘add to favourites’ link (the mongo _id in this case)
        – Loop through the localStorage array of objects to get an index for that unique id
        – Use this array index to do the update based on your/Nic’s code

        … which will abstract away some of the code so I can just push in any reference to any array in localStorage and change a key on that object.

        If you are saying that I can cut out my updateWhere() function, then that’d be even more awesome. Array object structure is like so:

        [
        {
        “_id”: “548adfb97ad531fc1dcb2e9f”
        “name”: “item one”,
        “colour”: “blue”,
        “favourite”: false
        },
        {
        “_id”: “548adfb97ad531fc1dcb2ea0”
        “name”: “item two”,
        “colour”: “green”,
        “favourite”: false
        },
        … and so on
        ]

        • Steve OConnor

          Just a thought ….
          There are lots of ways of skinning that cat, here is one approach of many

          (pardon my pseudo code, its close to a solution, but still full of bugs)

          And some UI code …

          So – clicking the checkbox hits the model, which writes into the array.
          Writing into the array triggers $localStorage to do its magic, and save the changes to the browser’s local disk.

          No ng-clicks being fired anywhere, and no looping through arrays looking for matches.

          There is only 1 line in the code above that mentions $localStorage, and thats all you need. Its a simple fire-and-forget sort of thing 🙂

          Now you just need a ‘Save to Cloud’ button, or whatever, and dump the whole of $localStorage.items up to the backend for safe keeping in mongo.

          Thats just a case of something equivalent to this on the backend :

          Hope that helps 🙂

          • Mike Brady

            Very nice! Thanks Steve. You’re using underscore for the findItemById function?

      • Mike Brady

        Ended up going with this:

        $scope.updateWhere = function(inputArray, key, searchValue, keyToChange, newKeyValue) {

        for(var co=0;co<inputArray.length;co++) {

        if(inputArray[co][key] === searchValue) {

        console.log(co);

        inputArray[co][keyToChange] = newKeyValue;

        }

        }
        };

        and the ng-click calls this:

        $scope.addToFavourites = function(index) {

        // Update where accepts (arrayObject, key, searchValue, keyToChange, newKeyValue)

        $scope.updateWhere($localStorage.itemList, '_id', index, 'favourite', true);

        };

        thanks for your help Nic and Steve

        • Anyway I could get you to edit your comment and put your code between code and pre HTML tags so it will format nicely?

        • No problem. Glad we were able to help 🙂

    • It should be possible. Think of ngStorage as a standard JavaScript object. As long as you know the object path, you can access and alter it directly. For example, say you have the following object:

      If you set that object to ngStorage like $localStorage = theObj; you should be able to alter the wasRead by doing:

      $localStorage.users.nraboy.todo[0].wasRead = true

      Now a lot of what I just wrote is more pseudocode, but it should work fine.

      Does that make sense?

      Regards,

      • Mike Brady

        Thanks for the quick reply! Yes, that makes sense. So I can actually change the value ‘in situ’? I don’t have to make something equal to the localStorage value and then change it? That seems like a bonus…

        • Yea, ngStorage makes life very easy 🙂

      • Mike Brady

        Worked a charm! Thanks a million Nic…

        • Awesome! Glad I was able to help 🙂

  • Steve OConnor

    Thanks Nic, that was a very cool thing to #include in my codebase. I already had a simple service defined in my existing code to wrap localstorage for shoving objects into … but that required using a getter/setter pattern, plus a couple of nasty hacks in the application to coerce things in and out of JSON in some obscure situations.

    This replacement service got rid of all that cruft, and cleaned up my application codebase, which is always a good thing.

    BEST bit about this (from my point of view), is reading how its implemented, and seeing a very clever use of a watch on $rootScope. Seeing an elegant use of this makes me a little more confident in writing more of my own code in the “true angular way” in future. Thats a big win for me.

    Sometimes, its a bit quicker up front to just code things “ye olde way” at the expense of a technical debt down the track. ngStorage is a GREAT example to show fellow coders how doing things the true angular way is not necessarily as hard as it looks.

    • I’m glad you learned something positive from this article 🙂

  • Didier

    Good Stuff!

  • venkatesh

    Can u provide me code for below requirement?
    one html page consists of only username and on a button click the the username entered in the textbox should be available in the other html page as username is so and so using without using session or cookie
    LIKE USING LOCAL STORAGE

    • Sorry, but I don’t make personalized example code. If you make an attempt at what you’re asking and run into issues, I’d be happy to help you troubleshoot, but I won’t do it for you.

      Using the resources found on my blog, you should be able to string together a functional prototype of what you’re looking for.

      Regards,

  • kevin jose

    Hello Nic your tutorials are really great ,thank you so much. I tried using the above example to make a simple todo app for offline access using ionic .. also i have made the same app using rest implementation with MEAN stack . Can I in any way sync my ng-storage data with mongodb data using ionic framework??

    • Hi Kevin

      I saw your Tweet to me, I just hadn’t had a chance to respond to it.

      First off, let me start by saying I have never used MongoDB before. With that said, I did a Google search and I couldn’t find any JavaScript connector libraries for it leading me to believe you’re going to need a middle-man server for a RESTful API. Again, I could be wrong on this as I didn’t too a whole lot of research.

      If you’ve got RESTful communication between your Ionic Framework application and the MongoDB, you could easily create an AngularJS factory that accomplishes sync. It wouldn’t be a quick process to accomplish, but I don’t see it being too hard.

      Hopefully this helps at least a little?

      Regards,

      • kevin jose

        Thank you Nic that was useful

    • Mahesh

      Hi kevin, have you find any solution for sync ?

  • Hello Nic, I have a question, ngStorage have some limit? like string length or max size? Thanks.

  • Vikas

    How do we monitor local storage? like expire it after a certain interval of time or only expire it after a certain time of no use?

    • You’d have to add your own logic. Every time you store something that needs to be expired, maybe store an expiration time with it and then do a check in your angular.module.run. Numerous ways to do this.

      Hopefully that helps.

      Regards,

  • adel sedighi

    can I use this as directive to cache dom elements on ng-repeat? what if I have several two way binding block in the segment which I want to cache?? does it watch for the change???

    • Can you give me a specific example of what you’re trying to do?

  • Lakmal Caldera

    Under the hood does ngStorage perform better than HTML5 localStorage(wrapper) or is it basically the same thing? All I see as a benefit is in its ease of usage!

    • It is the same thing. ngStorage just gives you convenience.

  • BeginnerBaby

    Hello Nic, your blog is very nice and helpful. am Jaay from India. am a final yr university student, currently am doing my final yr university project in JavaScript and AngularJs. i need your help complete my project.
    here let me explain my situation..

    well, am trying to upload users image file through button which is uploaded form their local machine.
    then
    it should save in some other driver’s folder in my machine as well as database

    if user upload their file using button, success message should arise like “your file has been uploaded successfully”

    then i want to view that uploaded image from my machine’s drive…!!!

    if it possible means. pls help me to fix this issue. am seeking complete code.

    hope you help me..

    Thanks in advance

    (forgive me for my bad English, if any)

    • Your comment is unrelated to the article. All unrelated questions or comments must be directed to my Twitter account.

  • vinnie

    Hi Nic, I want to use ngstorage for my app, but when I included the module it keeps my giving this error. Can you please help me out.

    Module ‘ngStorage’ is not available! You either misspelled the module name or forgot to load it. If registering a module ensure that you specify the dependencies as the second argument.

    Thanks
    Vinnie

    • Put your project on GitHub and I’ll take a look.

  • Jerome

    Hi Nic,

    Great post ! 🙂
    I am looking to a solution to store data locally (I use Ionic and Firebase).
    You said to use NgCordova but I saw this project too : https://github.com/grevory/angular-local-storage
    Is there really a difference between the two projects?

    Another option is angular-cache project.
    As I store images as base64 string, I am afraid to store more than 5Mb with NgCordova.
    How did you manage the fact storage exceed 5Mb?

    Thanks,
    Jérome

    • Since I don’t use that library, I can’t really compare the differences, but my assumption is that it is just another wrapper to HTML5 local storage like ngStorage.

      If you’re planning to store large files, I recommend you just use the filesystem rather than trying to store them in a data store.

      Regards,

      • Jerome

        Thanks Nic for your answer 🙂
        What do you mean by filesystem?

        • Oops, I forgot this was a web post and not hybrid mobile apps :-P. Sometimes I lose track.

          In the case of a web browser, this plan wouldn’t work. Unfortunately, I don’t have a solution for you to store large files locally. You might fiddle with browser caching or something.

          If you’re coming at this from a hybrid mobile app perspective, you might take a look at this:

          https://www.thepolyglotdeveloper.com/2014/09/manage-files-in-android-and-ios-using-ionicframework/

          It is slightly dated, but it should give you an idea. Store the file on the filesystem, and reference the name and location in your database.

          Regards,

          • Jerome

            Thanks for this post Nic.
            One big issue I got with files for now is that I use Firebase and base64 them is the easiest way to store them. I need files to be seen by lot of users and not only the current user.
            I could use another 3rd party (amazon s3, etc) but I prefer to wait that Firebase gets its own way to store files (I hope soon :D)
            Thanks,

  • Angelo Rigo

    Hi Nic ! great tutorial ! can i use ngStorage for a solution where the user can maintain the last pdf downloaded (when i do not have internet conection) and generate new pdf from form options. How do i keep track of the reference for this last downloaded pdf and delete it when i download a new one ? Thanks Ângelo

    • If you want to store the PDF in local storage you’ll have to convert the file bytes to base64 and then store the string. Web browsers won’t have any kind of file system storage.

      If you’re referring to hybrid app development, you’ll have to use the File plugin and implement your own logic for synchronization. Some information on the File plugin can be seen here:

      https://www.thepolyglotdeveloper.com/2014/09/manage-files-in-android-and-ios-using-ionicframework/

      Regards,

      • Angelo Rigo

        Thank´s Nic for sharing this tutorial, i just implement with a pdf file and it work´s ! the pdf download to the directory, will try to adapt to open the pdf i think i will need inappbrowser plugin.

      • Angelo Rigo

        Wich woud be the right angular way, to create a service for FileCtrl (frmo the tutorial) so i can pass the name of the pdf´s as a parameter? that´s because i have many controllers, each one with a diferent pdf file, to avoid file overwriting!

        • Yea I’d create a service for anything PDF. That way all your controllers must go through the service in the same fashion.

          Regards,

  • anantzoid

    Hi Nic, Thanks for the information. However, I have a small question:
    Which method would be more time and load efficient ? Using local storage and serializing-deserialzing the object,
    or importing the ngStorage library?
    Wouldn’t including another dependency increase the overall time taken for page load and make the DOM heavier?

    • You’re probably fine using either. ngStorage is just a lightweight wrapper that doesn’t making any DOM element alterations.

      I personally wouldn’t be concerned.

      Regards,

  • Johaness

    ngStorage cannot work with Karma so I suggest using another alternative for this.

    • I believe this is a known bug and they are working on a fix.

      Regards,

      • DannyGoncalves

        I spoke to the author of ngStorage in a github issue related to this, and he said that there should be no problem with Karma atm, just need to do the karma config file correctly

  • Dan

    Hi Nic, please help me convert this to store in local storage. I am also trying to setup a DELETE bookmarkwordpresspost from localStorage and I am stuck…

    Regards.

    • Before you throw code at me you should probably tell me what isn’t working

  • manish kogundi

    HI Nic, i have a web application which is having multiple tabs and i use ng grid i want to cache the ng grid data so that when i switch between the tabs i dont have to loose the data can you suggest me if i can use ng storage to store arrays or huge lists ?

    • Are you referring to multiple browser tabs?

      • manish kogundi

        No the tabs within application , refer to the attached image if i switch between different tabs highlighted in red or green , the data which is in ng grid below (highlighted in black) needs to be persisted how would i do that ?

  • Cos Callis

    Nic, great tutorial, but I am having a minor issue…of course it is with IE (all’s well in chrome)
    running my site from the local machine (visa-vi Visual Studio) all is also good, but when deployed to the staging server (staging.mysite.local) I get an access is denied exception in the browser’s console…
    Any thoughts on how to resolve this?

    • Access denied doesn’t sound like an ngStorage or local storage issue. Mind pasting the full log in the comments?

  • Harshdeep Sangwan

    Nic, I have been using localstorage to store data while developing in ionic framework but recently I encountered a problem i.e. when exiting the app, I lose all my data. Does this happen with ngstorage too? What are other alternatives to it?

    • I use ngStorage in my applications and the data persists when I restart my application. You might have some logic problems somewhere that is resetting your data.

      Regards,

      • Sadiq Ali

        where it will store the data? Is it in local machine or Is there any local memory in application like we have Isolated storage in silverlight? It will store data paermanantly?

        • It stores the data in the same location HTML5 local storage would. This is only a wrapper for local storage. Local storage is stored in your browser so as long as you don’t clear your data it will be there forever.

          Regards,

  • sandagolcea

    you really need to start using Emmet..

    • What is Emmet?

      • sandagolcea

        http://emmet.io/ It’s a package that helps you automate writing html; e.g. if you want 5 divs with class container and value 1, 2, 3..5 you’d write div.container{$}*3 + tab and it would create them automatically. Sorry but it’s just painful to watch you write html.

  • darrenking

    Hi Nic. Thanks for the post. Okay, so this is just in reference to one’s own local storage, right? What would be the simplest way to persist data, say for instance “reviews”, so that any user could access the site and have review info persist? I’m just trying to understand conceptually what would need to be set up differently – with the key word being “simplest”. 🙂 Thanks!

    • Yes ngStorage and HTML5 local storage is a reference to local browser or device storage only. If you want to sync data between local and remote you might check out this:

      http://blog.couchbase.com/sync-with-couchbase-using-only-angularjs-and-pouchdb

      I also have a few more tutorials like this coming since there are a ton of different ways to sync data between local and remote.

      Regards,

      • darrenking

        Thanks, Nic. I will check out the article.

  • R.O.

    Hello Mr NIC,
    Many thanks for all your tutorials that have greatly helped and helping us in so many ways.
    Please, i have problem at hands to solve though i’m a newbie in angular/ionic.

    1) I have a form that contains several inputs to collect personal info like names, gender, DOB, Occupation etc. At the bottom of the form i have image tag and a button to display and capture image respectively. I was able to capture and displayed the captured image.

    PROBLEM STATEMENT:
    1) I would like to save all the personal info including the captured image on a local storage. Why? because of bad network.

    2) I would like to retrieve the saved info and image and upload to a remote server.

    Please, i would be so grateful if you can illustrate this with a simple and short tutorial as you wish.
    Thanks once again.

    • Desire #1 can be accomplished many ways, but things start to get more tricky once you introduce desire #2. For both, I don’t think I’d recommend storing the images themselves in data storage. Your best bet is to store the images on the device file system and store the file meta data (name, location, etc.) inside some sort of data storage.

      If you’re feeling adventurous you could try this:

      http://blog.couchbase.com/using-couchbase-in-your-ionic-framework-application-part-1

      Otherwise, you may want to open a suggestion request for me here:

      https://www.thepolyglotdeveloper.com/2015/07/what-programming-tutorials-do-you-want-to-see/

      Best,

      • R.O.

        Thanks so much sir. I saw one of your tutorials on ngStorage. It’s awesome. Can i use it for my above concern? If so,how can i extend it to accommodate array of many objects?

        • Like I said, it depends on your plan. If you take my advice and store the image data on a file system, then sure. If you start storing large files in local storage I’m pretty sure you’re going to run into a mess of problems.

          Treat ngStorage like any other JavaScript object:

          Best,

    • sekar

      hi R.O,
      i would like to sync saved localstorage information to server?
      if u know any methods,kindly reply …..

  • Siddhesh

    after login of a particular user i want to display data of that particular user only so for that can we use your above approach ??

    • Well my guess is that your local / ngStorage will only contain data for the authenticated user, and not your entire remote database. What I’m trying to say is yes this could work, but it really comes down to the logic you implement both locally and server side.

      Regards,

  • m1nka

    Hey Nic,
    great post as always 🙂 I have a question though. If I publish an app in the appstore/playstore and publish an update , will the data persist ? Do you have any experience with that ? Assuming I use ngStorage/localstorage ? Thanks.

    • In my apps that I’ve published it persisted.

  • sudhir manne

    Hi how to update the saved localstorage values

    • The same way you would any JavaScript object

  • Mahesh

    Hi Nic, Do you have any plans to implement synchronization for ngstorage to Mongodb ?

  • Jemli Fathi

    Hi, how to test if a local storage entry exists?
    Because I treid the if(typeof $localStorage.entry == ‘undefined’) and it’s not working well

    • If you want to know if an entry is defined you probably want to do something like this:

      if(!$localStorage.hasOwnProperty(“entry”))

      Best,

      • Jemli Fathi

        Thank you very much

  • Keshav Bisarwal

    Hi Nic,

    What is the size limit of ngStorage for Android and IOS device ?

    Thanks

  • sekar

    hi nic,
    how to synchronize local storage information to server for offline web application?
    i have stored datas in localstorage by using ng-storage method..

    • Data synchronization is something best not explained in the comments of a blog. It is too huge of a topic. That said, if data sync is your goal, there are much better, already created plugins, libraries, and SDKs that will accomplish the job.

      For example have you seen Couchbase? http://www.couchbase.com

  • Sunit Vijayvargiya

    Hi Nic, Thanks for the nice tutorial.
    I am facing one issue.
    I am trying to give user 2 option Save and Upload. When i save it saves the form data in the localStorage and the upload works as well.
    Now the problem is when i try to refresh the page. I see that my select tag doesnot have the value which is stored in the localStorage.
    I have view like below.

    But in the controller the value for model testing is set from the localStorage.
    How can i show the same value in the view of the application i.e the Select tag.?
    The application is in angular javascript.
    Your help will be highly appreciated.
    Thanks

  • tarekahf

    Can you export objects saved in LocalStorage to a file to be saved on the local drive of the web application (on mobile device or desktop)? Then later, upon request by the user, to import the saved file back to LocalStorage to continue working with the save data since last session. Is that possible?

    • Typically front-end JS cannot access the file system.

  • Rahul Gulati

    if an api has more than 1000 pages, how do we store them all? Can we use factory service

    or do we need web sql

    how should it work. do we create app.factory call or we need to create a db in angular js

  • jaikhan

    Easy to understand….Thank you

  • Geoff

    hi nic sir our client is at dubai and i have created an ionic app for them they are asking that what ever data is there it should be stored in local how can i do it can you give me some example please?

  • tarekahf

    Hi Geoff, try this course, I think it should help you: https://app.pluralsight.com/library/courses/html5-offline-apps-angular-indexeddb-bootstrap
    Tarek

  • siddharth

    Hi Nic, How can we save an image/video data url/blob url to one of the folders in Windows system drives?

    Thanks – Siddharth

    • You cannot use front-end JavaScript to save to the filesystem.

      • siddharth

        Hi Nic,

        Thanks for the input. Actually I am using “var files = e.target.files;” and
        “var reader = new FileReader();” to get a .xml file instance. I want to append few xml tags to that file. Do you know any method/way that can be used to achieve this. Actually, I want to avoid any server, liferay or java usage to perform this functionality. I am unable to find any solution on the internet.

        Thanks – Siddharth