Saturday, July 26, 2014

Look Mom I'm FizzBuzzing in Chrome OR Intro to AngularJS

"Like captives bound to a triumphant car."
-- Shakespeare, Henry VI Part I
Act I, Scene I, Line 22

Tell me what you program in and I'll tell you how to FizzBuzz in it.

Not being an "UI guy" but wanting to become a Full Stack Developer the question came up, how do I do Code Katas using a more full stack approach?  How would I do FizzBuzz using AngularJS?

The great thing about AngularJS is that you can simply add it to whatever HTML you currently have meaning you can add it to your html tag, body, or even just a simple div.

Say you have some HTML like the following.


<html> <head> <link href="style.css" rel="stylesheet"></link> </head> <body> <h1> ng-fizzbuzz</h1> <div> <input /> <h1> FIZZBUZZ_RESULT</h1> </div> </body> </html>
You would like have an input box which will display the FizzBuzz value, thus given 3 in the input box will display Fizz and likewise 2 would give 2.  Let's add some simple JavaScript using AngularJS to FizzBuzz this.



Looking at this gist we see the following in the HTML:



We see we have three parts

  • ng-app => which Angular application are we going to use
  • ng-controller => which controller on the application are we going to use
  • ng-model => what data on the controller are we going to use
These parts align with the JavaScript code:


var app = angular.module('fizzbuzzApp', []);
 

names the application


app.controller('FizzBuzzCtrl', ['$scope',
function($scope) {
$scope.translate = function(value) {
var ret = "";
if (!value) return "";
if (value % 3 === 0) ret += "Fizz";
if (value % 5 === 0) ret += "Buzz";
return ret || value;
};
}
]);


defines the function for the controller

We do not see the value defined in the ng-model anywhere in the JavaScript code, so what gives?

{{translate(value)}}

calls the translate on the controller giving it the value of value bound in the ng-model on the input tag

This is one of the easier ways to do FizzBuzz with AngularJS.

This code is on Plunker: http://plnkr.co/edit/HMxS8H?p=info

Enjoy.