Twitter: raymondcamden


Address: Lafayette, LA, USA

AngularJS IndexedDB Demo

02-07-2014 8,175 views Development, JavaScript 18 Comments

Over the past few months I've had a series of articles (Part 1, Part 2, Part 3) discussing IndexedDB. In the last article I built a full, if rather simple, application that let you write notes. (I'm a sucker for note taking applications.) When I built the application, I intentionally did not use a framework. I tried to write nice, clear code of course, but I wanted to avoid anything that wasn't 100% necessary to demonstrate the application and IndexedDB. In the perspective of an article, I think this was the right decision to make. I wanted my readers to focus on the feature and not anything else. But I thought this would be an excellent opportunity to try AngularJS again.

For the most part, this conversion worked perfectly. This may sound lame, but I found myself grinning as I built this application. I'm a firm believer that if something makes you happy then it is probably good for you. ;)

I still find myself a bit... not confused... but slowed down by the module system and dependency injection. These are both things I grasp in general, but in AngularJS they feel a bit awkward to me. It feels like something I'll never be able to code from memory, but will need to reference older applications to remind me. I'm not saying they are wrong of course, they just don't feel natural to me yet.

On the flip side, the binding support is incredible. I love working with HTML templates and $scope. It feels incredibly powerful. Heck, being able to add an input field and use it as a filter in approximately 30 seconds was mind blowing.

One issue I ran into and I'm not convinced I created the best solution for was the async nature of IndexedDB's database open logic. AngularJS has a promises library built in and it works incredibly well for my application in general. But I needed the entire application to be bootstrapped to an async call for database startup. I got around that with two things that felt a bit like a hack.

First, my home view (get all notes) ran a call to an init function to ensure the db was already open. So consider this init():

function init() {
		var deferred = $q.defer();

		if(setUp) {
			deferred.resolve(true);
			return deferred.promise;
		}
		
		var openRequest = window.indexedDB.open("indexeddb_angular",1);
	
		openRequest.onerror = function(e) {
			console.log("Error opening db");
			console.dir(e);
			deferred.reject(e.toString());
		};

		openRequest.onupgradeneeded = function(e) {
	
			var thisDb = e.target.result;
			var objectStore;
			
			//Create Note OS
			if(!thisDb.objectStoreNames.contains("note")) {
				objectStore = thisDb.createObjectStore("note", { keyPath: "id", autoIncrement:true });
				objectStore.createIndex("titlelc", "titlelc", { unique: false });
				objectStore.createIndex("tags","tags", {unique:false,multiEntry:true});
			}
	
		};

		openRequest.onsuccess = function(e) {
			db = e.target.result;
			
			db.onerror = function(event) {
				// Generic error handler for all errors targeted at this database's
				// requests!
				deferred.reject("Database error: " + event.target.errorCode);
			};
	
			setUp=true;
			deferred.resolve(true);
		
		};	

		return deferred.promise;
	}

This logic is similar to what I had in the non-framework app but I've made use of promises and a flag to remember when I've already opened the database. This lets me then tie to init() in my getNotes logic.

	function getNotes() {
		var deferred = $q.defer();
		
		init().then(function() {

			var result = [];

			var handleResult = function(event) {  
				var cursor = event.target.result;
				if (cursor) {
					result.push({key:cursor.key, title:cursor.value.title, updated:cursor.value.updated});
					cursor.continue();
				}
			};  
			
			var transaction = db.transaction(["note"], "readonly");  
			var objectStore = transaction.objectStore("note");
            objectStore.openCursor().onsuccess = handleResult;

			transaction.oncomplete = function(event) {
				deferred.resolve(result);
			};
		
		});
		return deferred.promise;
	}

All of this worked ok - but I ran into an issue on the other pages of my application. If for example you bookmarked the edit link for a note, you would run into an error. I could have applied the same fix in my service layer (run init first), but it just felt wrong. So instead I did this in my app.js:

$rootScope.$on("$routeChangeStart", function(event,currentRoute, previousRoute){
		if(!persistanceService.ready() && $location.path() != '/home') {
			$location.path('/home');
		};

	});

The ready call was simply a wrapper to the flag variable. So yeah, this worked for me, but I still think there is (probably) a nicer solution. Anyway, if you want to check it out, just hit the Demo link below. I want to give a shoutout to Sharon DiOrio for giving me a lot of help/tips/support while I built this app.

p.s. I assume this is obvious, but I'm not really offering this up as a "Best Practices" AngularJS application. I assume I could have done about every part better. ;)

18 Comments

  • Laurence #
    Commented on 02-10-2014 at 4:23 PM
    The demo appears to be kaputt in Chrome.
  • Commented on 02-10-2014 at 4:24 PM
    Working for me. What error do you see in DevTools?
  • Laurence #
    Commented on 02-10-2014 at 4:51 PM
    My mistake. I assumed that because the Resources tab listed IndexedDB that the browser supported it (go figure), but when I checked the actual version, I only add v22.0.xxx. The error in the console is "TypeError: Cannot call method 'open' of undefined" not that it matters now.
  • Commented on 02-10-2014 at 4:54 PM
    Well, this is a great comment though. I really should have added an error for it.
  • Commented on 02-10-2014 at 5:11 PM
    So I have a fixed version but am having difficulty hitting my FTP server inside my corp network. I'll push up a fix later tonight. Thanks for pointing this out.
  • Commented on 02-10-2014 at 9:25 PM
    I pushed up a fix - let me know if it works for you. (And by fix I mean it should at least tell you that your browser isn't supported.)
  • Laurence #
    Commented on 02-11-2014 at 9:28 AM
    Looks good. The demo is showing the error message now.
  • Jens #
    Commented on 02-24-2014 at 2:13 PM
    Great article. We build a webapp with offline support (20.000 records) for mobile (websql) and desktop(indexeddb) and I would love to try this approach when I ever get around rebuilding this based on a proper framework
  • Thiago Costa #
    Commented on 03-18-2014 at 9:54 AM
    Hello. I'm from Brazil.
    First, congratulations for post.

    I've demand that I need synchronize Local Storage with server side, more exactly with indexeddb.
    In this case, my server side is Java.
    Do you know any example about it ?
    I didn't find out about it.
    I really appreciate all the help you'll give me. Or suggestions how to resolve this.

    Other thing.. I tried to copy your demo 'AngularJS IndexedDB Demo' but It doesn't work.
    It appears trouble with angular.js. Do you have code in Git repository ?

    Thanks a lot.
    Sorry my poor english, I've been studying for 2 months :)
  • Commented on 03-18-2014 at 4:37 PM
    "In this case, my server side is Java.
    Do you know any example about it ?"
    Nope. Sorry. In theory it isn't too complex. I know how it would be done with ColdFusion, and can imagine it in Node, and the process is relatively the same for each. The difference is just in how you build it.

    "Other thing.. I tried to copy your demo 'AngularJS IndexedDB Demo' but It doesn't work.
    It appears trouble with angular.js. Do you have code in Git repository ? "

    Can you describe how it doesn't work? What error do you get exactly?
  • Thiago Costa #
    Commented on 03-19-2014 at 7:39 AM
    Thanks for answer.
    I've been searching for examples, anyway thanks a lot.

    When I had copied your code shows me error about javascript, but it wasn't.
    But I'd seen this morning and the code source has reference to files 'partial/home.html' 'partial/edit.html' and so on.
    I think it could be problem.

    If necessary, I can send you an email with content in annex.
    Now, The example doesn't show problem on firebug, but it doesn't work too, only blank page.
  • Thiago Costa #
    Commented on 03-19-2014 at 8:31 AM
    I forget. I'd commented where there were references to folder 'partial/xxx.html'
  • Commented on 03-19-2014 at 8:37 AM
    Please share the URL of where I can test the app. Please share it here though so others can see as well (and may be able to respond quicker than I can today).
  • Commented on 03-19-2014 at 1:10 PM
    Ah, you don't have all the files. It is a pain to make you grab all the files by hand, so I'll make a zip.
  • Commented on 03-19-2014 at 1:12 PM
    Here you go: https://dl.dropboxusercontent.com/u/88185/angulari...
  • Thiago Costa #
    Commented on 03-19-2014 at 1:23 PM
    Sorry, I'm newbie yet.
    Thanks for attention.
  • laza #
    Commented on 07-21-2014 at 8:23 AM
    Hi!

    I'm fresh developper, how can I synchronise front db to my server db using api-service.

    Thx in advance.
  • Commented on 07-21-2014 at 8:45 AM
    Your question is kinda big, I'll answer at a high level, but obviously it depends on your back end service too. Also, it depends on how you want to handle conflicts. Is the server the 'master' and your client side db just a slave? if so, you need to find out what changed on the server and make those changes to the client, including new content, edited content, and deleted content.

Post Reply

Please refrain from posting large blocks of code as a comment. Use Pastebin or Gists instead. Text wrapped in asterisks (*) will be bold and text wrapped in underscores (_) will be italicized.

Leave this field empty