Angular.js and data binding

A few weeks ago in a burst of creative energy, I decided it was time to take another stab at overhauling my shopping list site. This time I’m forcing myself to learn a new framework, Angular, which has something very cool that I want to get to know better for professional development: data binding.

The basic idea behind data binding is that it creates a two-way link between an element that you see on the screen (like a button or text box) and a variable or object in the data structure generated by your code. This two-way link automatically handles keeping the two in sync, which is a big time saver for a language like Javascript where updating UI elements can be quite messy (depending on how much jQuery you use, maybe).

Here’s the basic structure of the shopping list now:

There are at least two really cool things going on here:

The “ng-repeat” attribute on the table row tells Angular to repeat this row once for each item in the “shoppingList” data structure. This means I don’t have to worry about managing the actual HTML of the list, it’s just created for me. My HTML markup doesn’t ever get hugely long and complex, and it doesn’t have to be generated by Javascript so it’s much easier to read.

The “ng-model” attribute on the checkbox sets up automatic two-way data binding between the checkbox’s state and the value of the “item.isGotten” field. When I click the checkbox, .isGotten gets set to true; when I unclick it, it gets set to false. This saves me having to write the worst kind of click event handling code. It’s not just making programming faster, it’s making it more fun by letting me spend all my time thinking about the data structures and algorithms instead of the mundane glue.

The Javascript behind this is also much simpler than the old ugly version that had to handle parsing, generating HTML, handling events, and all that. It doesn’t save to the server quite yet, but it’s almost there. Because data binding handles all the basic syncing, I only have to define the logic for how to add and remove items from the list. The savings in lines of code is something like 80%.

This is simple and clean in a way that warms my heart. Most fun I’ve had with web development yet!

This entry was posted
on Friday, April 12th, 2013 at 11:23 pm and is filed under Programming.
You can follow any responses to this entry through the RSS 2.0 feed.
You can leave a response, or trackback from your own site.