AngularJS Counter Directive

23 Jun 2013

I was browsing around some e-commerce site and I saw a nice little quantity field - one that had a decrement and increment button on each of its sides and that got me thinking that it would be nice to have an AngularJS directive that can handle all that for us. So I started on it.

I'm very well aware of the HTML5 number input field type, but those fields aren't easy to style - in fact, I don't think it's possible to style them.

This solution will work across all the browsers and you can change the style to suit your website or web app easily.

Straight to the point

Here is the final product.

Setup

Simply copy the directive from the source and attach it to a new module or to an existing module.
The example above uses the default module that is generated when creating a new AngularJS Plunk.

Usage

In my controller

function MyCtrl( $scope ) {
    $scope.quantity = 4;
}

In my view

<div counter value="quantity" min="1" max="30" step="2" editable></div>    

Pretty simple, isn't it?

Explanation

We have declared that the div above will be handled by the 'counter' directive.
The counter directive expects a value attribute and will throw an error if that's not provided.
The value must be an attribute that is defined on the scope. The directive will set-up a 2-way data-binding - meaning, in our example, the quantity attribute will automatically be update with the value in the counter.

The other optional attributes are min, max, step and editable.

Min and max are self-explanatory, they basically set a range to restrict the value.
Step defines how much the value is incremented or decremented by with every click of the plus/minus buttons.
And finally, editable defines whether or not the field itself is readonly or not. Unlike all the other optional parameters, editable does not require any value.

When the field is editable, I have added some validation to ensure that non-numeric characters are automatically stripped out.

That's basically it.

I'd like to thank Kirk Bushell for his help with the 2-way data-binding that I was stuck with :D thanks, buddy!

My First Post - An Introduction

22 Jun 2013

The name is Maikel (pronounced: Maikel... or Michael), I'm a PHP Web Developer from Sydney, Australia.

I started my career as a Multimedia Designer, but quickly moved into the web development world as it was much more exciting to me.

Now I'm a PHP Web Developer, as well as a Front-end Developer, a badass Laravel and AngularJS developer. Laravel and AngularJS are by far my favourite tools for creating web apps, I'm hoping that I'll get a chance to write a few articles on those topics.