Saturday, November 5, 2016

an excuse to use a filter in an AngularJS 1.5.8 app

A coworker once showed me an example of a filter that he wrote which pluralized some (a majority) of English words correctly. I'm ripping off his idea here:

app.filter("sOnTheEnd", function () {
   return function (number, word) {
      if (word === undefined) {
         return number;
      }
      var pattern = number + " " + word;
      if (number == 1) {
         return pattern;
      } else {
         return pattern + "s";
      }
   };
});

 
 

I call out to it with the double curly braces syntax like so:

{{ book.numberOfPages|sOnTheEnd:"page" }}

 
 

You will note that I've baked in some extra love to keep "undefineds" from showing up in the HTML when this is attempted:

{{ book.numberOfPages|sOnTheEnd }}

No comments:

Post a Comment