Code Buckets

Buckets of code

Angular

Simple String Concatenation Filter for AngularJS

I’m currently tinkering around with Angular JS. I’ve always liked JavaScript and since there is currently one or two (thousand) JavaScript frameworks around I thought I would have a go at the Angular. It wasn’t immediately obvious how to cleanly concatenate strings for display so I wrote a filter and it works quite nicely. As ever I’m not making any claims for this to be technically brilliant but it does work, I wrote it with my own coding fingers and I like it.

The Demo

The demo system for this is a simple search for books using the Google Books API. The results display on an infinite scroll. That’s totally irrelevant to this but again I like it. The demo project code is on github at https://github.com/timbrownls20/BookShelf.MEAN.Stack

The Problem

Books have multiple authors. The Google API returns them in an array i.e.

"volumeInfo": {
 "title": "Baptizing Harry Potter",
 "subtitle": "A Christian Reading of J.K. Rowling",
 "authors": [
 "Luke Bell", “Another Author”
 ]}

We display them on the view with a simple binding

<h4>{{item.volumeInfo.authors}}</h4>

But unfortunately the display looks rubbish

no-string-concat

The Solution

We could display them correctly by putting a bit of looping logic in the view but I see enough abuse of views in my day job (and I’m guilty of some of it myself) so I would rather not continue view abuse in my spare time. So let’s whip up a filter. It will be cleaner and reusable.

To implement create a file called filters.js and pop in this

(function () {
 'use strict';

angular
 .module('app')
 .filter('stringConcat', function () {
   return function (input, delimiter) {
     if (input) {
       return input.join(delimiter)
     }
     else {
       return '';
     }
   };
 });

It’s embarrassing straightforward. An array and a delimiter in, join and return. We added it directly into our angular application which is imaginatively called ‘app’. It’s then available to be called in the view with a PowerShell style pipeline i.e.

<h4>{{item.volumeInfo.authors | stringConcat:', '}}</h4>

Don’t forget to reference the new file in the view (html page)

<script src="app/filters.js"></script>

And that’s it, everything looks a lot better.

string-concat

It’s available to use generally in the application whenever we need to concatenate strings. Lovely and easier to implement than I remembered.

Useful Links

Documentation for AngularJS filters can be found at
https://docs.angularjs.org/api/ng/filter/filter

and an end to end tutorial including filtering is at
https://docs.angularjs.org/tutorial/

 

 

LEAVE A RESPONSE

Your email address will not be published. Required fields are marked *