Hash Sync (Angular Directive)

I may have cheated a bit this week. The contents of this article just about mirror the README from this plugin's repo. I wanted to share it nonetheless, and I can't think of a lot I want to say in the one that I wouldn't want to say in the other.

Hash Sync is an AngularJS directive for syncing a model with the URL hash.

The goal of this module is to be able to automatically sync model changes to the URL's hash and back.

Use Case

The use case would be to easily recreate a form state without any session/localStorage variables (i.e. so it could be shareable, or recreated on another computer quickly and easily).

As a specific example, libraries, such as jQuery UI will keep track of the options you choose in a custom download, and you can use that URL to revisit the page and have all your options you had selected selected again.

This module was created to be a more robust, "drop-in" solution inspired by things like jQuery UI's custom download page.

Usage

Just add a hash-sync attribute to anything that can also usin the ngModel directive (which is required for this to work).

<input type="text" hash-sync ng-model="test">

That's all there is to it! Now change the value in the input to say, "Banana" and see that it syncs (both ways) between the hash in the URL and the value in the input. The URL will now have #test=Banana in the URL. Note that you do have to hit enter in the URL bar to actually change the hash value (it's not enough to just type in there).

Important: Don't forget the following in your config, which is needed for the hash tag to work without affecting Angular routing:

app.config(function ['$locationProvider', ($locationProvider) {
    $locationProvider.html5Mode(true).hashPrefix('!');
}]);

Location History

By default, the directive will replace history (via $location.replace() (see Replace method section in the Angular docs for $location). This means that updating a text field does not create a place in history (i.e. without this, you could hit back to undo every change to any hash-sync input and that's usually not desirable).

If you do want it to create a new item in the history, you can add a replace-history="false" to the element, and this will create instead of replace in the location history.

Demo and Repo

Demo: http://cwspear.github.io/hash-sync/
Repo: https://github.com/CWSpear/hash-sync