Categories
AngularJS

Fixing autocomplete (autofill) on AngularJS form submit

Many browsers support autocomplete but do not trigger “change” events on inputs when the user initiates autocomplete. This is a problem for many libraries and code in the wild that rely on performing some action (e.g. input validation) when input data change.

With respect to AngularJS forms, the problem becomes obvious if you are using AngularJS form validation. If you autofill an empty form then press Submit, AngularJS will think the inputs are still empty:

AngularJS unaware of autofilled inputs
AngularJS unaware of autofilled inputs

Here is a simple login form subject to this issue:

Unfortunately the underlying issue of not having an appropriate event related to autofill must be addressed by browser vendors. However in the meantime, we can use a custom directive to ensure AngularJS knows about form changes made by autofill at time of form submit.

Patch directive

In CoffeeScript

In JavaScript

Directive in use

The directive is simple to use; just apply it to your form and away you go:

Categories
AngularJS

Decoupling JS and HTML with AngularJS

The primary reason for the influx of interest in JavaScript MVC frameworks is improving separation of concerns between HTML and JS. I’m going to demonstrate why decoupling of HTML and JS is so important and how AngularJS helps solve the problem.

Why decoupling is so important

Traditional DOM selection, traversal, and manipulation is the root of tightly coupled HTML and JS—and the bane of a front-end developer’s existence. It’s not that it is difficult to write or understand, but rather that it is exceedingly difficult to maintain. Even the most seemingly innocuous JS containing node names, CSS classes, or event bindings causes a tightly coupled architecture to quickly emerge. Consider a simple jQuery app that lets the user arbitrarily add items to a list:

I took it a step further than many jQuery apps in the wild by introducing a rudimentary template for the list item rather than compositing the item entirely in JS. However, the app still naturally suffers from some serious coupling. Here are a few realistic scenarios the app might face in the future:

  1. Multiple vehicle entry methods needed.
    • Will need to change element selection by ID to selection by class.
    • Will need to adjust DOM selection in JS.
    • What is conceptually a change only to HTML clearly will also require changes to JS.
  2. List item template changes.
    • Will need to change template DOM selection and manipulation in JS.
    • Same as above; conceptually HTML-only, actually not.
  3. Multiple displays of garage needed.
    • Similar problems as #1 and #2.

The code changes required to implement these features are significant and involve disparate contexts and thus are costly and prone to error. Here is a simple diagram to visualize the coupling:

Separation of concerns

Surely there must be a better way. Consider how the diagram above might change if we introduce MVC-inspired separation of concerns:

Enter AngularJS

Here’s the same app using basic AngularJS instead of jQuery. (If you’re keen on UX, you’ll notice I left out a few usability features from the previous example. We’ll add those back momentarily using more advanced AngularJS techniques.)

The DOM selection, traversal, and manipulation disappear! What you see is effectively the diagram of the three circles—the vehicle data is now abstract and the DOM and JS coupling is virtually eliminated. The three “what ifs” mentioned before which are conceptually HTML-only changes now actually are HTML-only changes since the underlying data model doesn’t change (and the JS is only referencing the abstract data model).

If I add only a little bit of HTML on the view layer, I get cool new features that operate on the same data set—no changes to JS required (conceptual view-only change now a reality):

Usability sugar as promised




So you may have noticed a few UX niceties in the jQuery version of the app that we lost later on:

  • Vehicle name input focused after changing vehicle type.
  • Vehicle name input focused after clicking submit button with empty name and getting “name required” error.
  • Vehicle name input focused after clicking submit button and successfully adding a vehicle.

Doing this in AngularJS is to some extent another topic—still along the lines of separation of concerns, but not exactly MVC—very specific to the problem domain of the DOM. The way AngularJS solved this particular problem is clever, unique among JS frameworks, and extremely robust; the solution is in what are called directives, “a way to teach HTML new tricks.” What I am doing here is essentially inventing a couple new HTML element attributes that will abstract out the concept that is focusing an input on various cues:

Note the new directives focusAfterChange and focusIf defined in the JS along with associated usage in HTML as <input ...="" focus-after-change="..." focus-if="..."/>, which elegantly encapsulates the behavior and still manages to abstract away DOM selection, etc.

Comments or questions are always welcome!

Categories
Developer tools

HTML5 Canvas Gradient Creator

There are plenty of CSS3 gradient creators out there, but much to my surprise there was not a single gradient creator for HTML5 <canvas /> to be found. Thus I present to you the only one of its kind, the HTML5 Canvas Gradient Creator.

Features

  • Visual point-and-click, drag-and-slide creation of gradients for HTML5/JS canvas
  • 1-n color stops; as many as you need
  • 0-255 bit alpha support
  • Linear and radial gradients
  • Linear gradient rotation
  • Radial gradient inner and outer circle position
  • Elliptical radial gradients
  • Saving of custom presets (browser local storage)
  • Valid, commented HTML5 and JS code output
  • Responsive design

Minimum compatibility

This is minimum compatibility for usage of this tool, as well as for gradient code generated by this tool. Earlier versions of Chrome, Safari, or Opera might be supported.

  • Chrome: WinXP/OS X SL Chrome 14
  • Firefox: WinXP FF4 (FF3 for gradient code generated by tool), OS X SL FF5
  • IE: Win7-8 IE9*
  • Safari: WinXP/OS X SL Saf 4
  • Opera: WinXP Opera 10, OS X SL Opera 11.1

* Inclusion of FlashCanvas or excanvas might enable support for gradients in earlier versions of IE.

Languages and libraries

Check out the source on Github.

Categories
AngularJS

Old Fashioned Metronome in AngularJS, HTML5, and CSS3

This went from a fun Saturday project inspired by a suggestion from my brother to a weekend-long, no-holds-barred tapping into some of the more powerful browsers’ HTML5 and CSS3 feature sets within the context of AngularJS. Check out the full screen app here.

Old Fashioned Metronome App

Features

  • Responsive
  • Can update the tempo while metronome is on (try tabbing focus to the bob, then using arrow keys to move it while it is swinging)
  • HTML5 Audio API
  • CSS animation
  • Fancy but not very practical source code view buttons to the right. (Just View Source or see the fiddle, it’s much easier lol.)

Libraries, frameworks, etc.

Compatibility as of 12/31/2012

Windows
  • Chrome 23.0 all features OK
  • Firefox 17.0 all features OK
  • Safari 5.1.7 all features except audio OK
  • Opera 12.12 all features OK
  • IE 10 nothing appears (due to use of background-size + background-position?)
OS X
  • Chrome, Safari all features OK
Mobile

Pshhh… Yea, right! Firefox and Opera on my Android are close but are missing key features.

Other

Used Ceaser CSS Easing Tool to create the custom
easing function for the wand “return to center” animation.

Categories
AngularJS

Make AngularJS $http service behave like jQuery.ajax()

There is much confusion among newcomers to AngularJS as to why the $http service shorthand functions ($http.post(), etc.) don’t appear to be swappable with the jQuery equivalents (jQuery.post(), etc.) even though the respective manuals imply identical usage. That is, if your jQuery code looked like this before:

You may find that the following doesn’t exactly work for you with AngularJS out of the box:

The problem you may encounter is that your server does not appear to receive the { foo: 'bar' } params from the AngularJS request.

The difference is in how jQuery and AngularJS serialize and transmit the data. Fundamentally, the problem lies with your server language of choice being unable to understand AngularJS’s transmission natively—that’s a darn shame because AngularJS is certainly not doing anything wrong. By default, jQuery transmits data using Content-Type: x-www-form-urlencoded and the familiar foo=bar&baz=moe serialization. AngularJS, however, transmits data using Content-Type: application/json and { "foo": "bar", "baz": "moe" } JSON serialization, which unfortunately some Web server languages—notably PHP—do not unserialize natively.

Thankfully, the thoughtful AngularJS developers provided hooks into the $http service to let us impose x-www-form-urlencoded on all our transmissions. There are many solutions people have offered thus far on forums and StackOverflow, but they are not ideal because they require you to modify either your server code or your desired usage pattern of $http. Thus, I present to you the best possible solution, which requires you to change neither server nor client code but rather make some minor adjustments to $http‘s behavior in the config of your app’s AngularJS module:

[box type=”info”]Do not use jQuery.param() in place of the above homegrown param() function; it will cause havoc when you try to use AngularJS $resource because jQuery.param() will fire every method on the $resource class passed to it! (This is a feature of jQuery whereby function members of the object to parametrize are called and the return values are used as the parametrized values, but for our typical use case in AngularJS it is detrimental since we typically pass “real” object instances with methods, etc.)[/box]

Now you can go forward with using $http.post() and other such methods as you would expect with existing server code that expects x-www-form-urlencoded data. Here are a few sample frames of the final result for your day-to-day, end-to-end code (i.e. what you hoped and dreamed for):

The HTML template

The client code (AngularJS)

The server code (PHP)

Other notes

So you may wonder now, is it possible for PHP to read the JSON request from stock AngularJS? Why, of course, by reading the input to PHP and JSON decoding it:

Obviously the downside to this is that the code is a little less intuitive (we’re used to $_POST, after all), and if your server-side handlers are already written to rely on $_POST, you will now have to change server code. If you have a good framework in place, you can probably effect a global change such that your input reader will transparently detect JSON requests, but I digress.

Thank you for reading. I hope you enjoyed my first POST. (Get it?!)

[box type=”info”]EDIT March 12, 2014: Moved the param() function def up a level to help interpreter only create one such instance of that function.[/box]