Menu Navigation Menu

Angular.jsOn a recent project we used Angular.js for some heavy lifting on the frontend. The framework has a steep learning curve but is pretty powerful once understood. A simple example of this is a currency filter for numbers passed into the view.

Angular has a built in currency filter and it works fine for basic uses with our US currency: it'll turn 9258 into $9,258.00. Great, but there are two problems here. First, many of our clients have their sites set on a global marketplace where currencies come in many different flavors and orders and second, the '$' can be ambiguous as it is used for the US Dollar, Canadian Dollar and the Australian Dollar.

Accounting.js is a small javascript library that solves the problem of currency symbol placement and periods vs. commas vs. spaces as separators. It is pretty straightforward to use:

accounting.formatMoney(4999.99, "€", 2, ".", ","); // €4.999,99

This works great, but of course, we don't want to pass all our settings to the view and can accomplish this in a cleaner way. Seems like a perfect place for a filter. Angular's filters are very similar to Rails' view helpers (or presenters) in that they move messy logic that needs to be handled at the view layer out of the view and into a separate, testable area of the codebase. Here is an example of our modified currency filter that uses Accounting.js' formatMoney() function:

// sample use {{ value | currency:"USD" }}
angular.module('filters', []).filter('currency', function() {
    return function(number, currencyCode) {
      var currency = {
        USD: "$",
        GBP: "£",
        AUD: "$",
        EUR: "€",
        CAD: "$",
        MIXED: "~"
      thousand, decimal, format;
      if ($.inArray(currencyCode, ["USD", "AUD", "CAD", "MIXED"]) >= 0) {
        thousand = ",";
        decimal = ".";
        format = "%s%v";
      } else {
        thousand = ".";
        decimal = ",";
        format = "%s%v";
      return accounting.formatMoney(number, currency[currencyCode], 2, thousand, decimal, format);

There might be better ways to work through the different scenarios needed but the idea is to move the logic into one place and out of the view. Now, our view only needs to be passed an amount (item.price) and a currency (item.currency):

{{ item.price | currency:item.currency }}

This will yield the following:

$1.99 USD
€4.999,99 EUR
$96.99 AUD
£45,678.90 GBP

This is a simple example and filters are a very basic part of the Angular framework, but hopefully it illustrates how Angular adds some nice organization to the madness of front end javascript. Whether we like it or not, the future of the web will get more and more complicated and Angular is a great way to satisfy these requirements.

Contact us for a complimentary 30 minute consultation.

get in touch