Programming blog by Ezekiel Victor

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:

read more

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!

read more

Solving AngularJS empty select option caused by jQuery UI effect

If you’re anything like me, while working with AngularJS you will soon want to integrate your “standard library” of jQuery and UI plugins into AngularJS directives. Recently on the job, I wrote an AngularJS directive to apply a jQuery UI effect to an element—I wanted to briefly shake a small form if an input was invalid (such as you often see in native app GUIs). The directive looked something like this:

Much to my surprise, during the shake effect a <select /> in the form went from having a non-empty option selected to having an empty option selected, and there was not an empty option in the select to begin with.

You may already be familiar with a select in AngularJS “mysteriously” gaining an empty option. That’s not mysterious at all as it turns out; it is reasonable behavior when the model associated with the select is not given a valid value. Here is a quick sample to demonstrate this problem and solution:

This was clearly not the problem I experienced. I had initialized the model correctly, and the empty selected option only appeared after the jQuery UI effect had finished. Admittedly, I still don’t know what jQuery UI is doing to cause this. However, without delving into the core of jQuery UI, I do at least have a solution to the problem for now; the answer lies in using ng-options instead of <option /> elements.

Here is a sample of the problem and solution side by side. Switch to the Result tab, then click the “Shake” button to see one select lose its value and the other retain its value as desired.

Cookie to the first person who can say what jQuery UI is doing to trigger the problem when using <option /> elements vs. ng-options!

read more

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.

read more

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:

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.)

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?!)

EDIT March 12, 2014: Moved the param() function def up a level to help interpreter only create one such instance of that function.
read more