Angular Project Blackjack: 9 – Game Service

(This post is part of my “from scratch” AngularJS project. If you are feeling lost, the first post is here.)

Back to it

We’ve got a good setup now, with our gulp file building and running as necessary. Let’s move back to working on our code!

A Game Service

In our GameController we have the ability to deal a hand of cards but we can’t really do anything with it yet. To do so, we need to start putting the blackjack game rules into our application. Let’s create a GameService to start handling these rules for us. The main thing our GameService will do for now will be to take a hand of cards and return the numeric value of that hand. We can then use that value in our controller to enable/disable actions a user can take on the hand.

Read More »

Angular Project Blackjack: 7 – File Concatenation with Gulp

(This post is part of my “from scratch” AngularJS project. If you are feeling lost, the first post is here.)

We’ve created quite a lot of files in just our application so far. Unfortunately, for every one of those files, it means we need to add an include to our index.html file and increase the request count for visitors just to load the app. Wouldn’t it be nice if we could just package all of our code into one file and just load that file in the application? That’s exactly what we’ll set out to do here.

There are a TON of applications that will get us the end result we are looking for: browserify, require, webpack, etc. Although, in my opinion, the simplest and easiest to understand is gulp-concat. At its very basic form, gulp-concat literally merges the files you give it into one output file. To get it going, we’ll need to have gulp installed, and get to gulp installed, we really should know what it is doing first!

Read More »

Angular Project Blackjack: 6 – Do You Even TDD Bro?

(This post is part of my “from scratch” AngularJS project. If you are feeling lost, the first post is here.)

Previously, I had mentioned that test driven development hasn’t really “stuck” for me and I find myself switching back to BDD for the most part. I find that this is usually because I don’t plan features out far enough in advance and I’m more of the “experiment and refactor” kind of developer. I have found instances where TDD actually works better for me, and today’s topic is one of those instances.

We are going to be working on the card service. This service will allow us to get a deck of cards, shuffle the deck, deal from the deck. Since this blackjack project is a game based off of set rules, we know how the cards should behave. We can write tests against these rules and then we’ll write our service to meet the rules. The rules are:

  • We should be able to get a new deck of cards with the object type “Deck”
  • The deck should contain 52 cards
  • There should be no duplicate cards in a deck
  • Each card should have a rank and a suit.
  • We should be able to ‘deal’ a card from a deck that has undealt cards in it.
  • Attempting to ‘deal’ from a deck with no undealt cards returns false
  • When a card is dealt, it is no longer in the cards array
  • We should be able to shuffle the deck and randomize all undealt cards.
  • We should be able to ‘reset’ a deck that will move all dealt cards into the undealt status and shuffle.

Now let’s write those tests:

Read More »

Angular Project Blackjack: 5 – Player Service

(This post is part of my “from scratch” AngularJS project. If you are feeling lost, the first post is here.)

Now that we have used views, directives and controllers, let’s move on to another big part of the AngularJS library, “Services”. If you’ve used angular for any amount of time, I’m pretty sure you’ve already googled “What is the difference between service, factory and provider?”. I know I have and I still haven’t fully grasped it yet. The best answer I can give is that if you need it to be runtime configurable, use a provider. Otherwise, use a factory. Why? Because John Papa said to! Services and factories are nearly identical, but using the revealing module pattern, you can make them really look like header and implementation files, which makes the Objective-C developer in me very happy!

Read More »

Angular Project Blackjack: 4 – Game Directive

(This post is part of my “from scratch” AngularJS project. If you are feeling lost, the first post is here.)

Going back to our first controller, we had to throw a lot of code into our shell.html file to display our game. This code had to know a lot about how the GameController functioned and if we wanted to have multiple copies throughout the application, we would need to duplicate this code every time.

Thankfully, AngularJS gives us the ability to place complex objects into our html code with very simple format. This ability is called angular “directives”. Angular is built on directives. In fact, we’ve already used a few built in directives in the shell.html file: “ng-if”, “ng-controller”, “ng-click”. Let’s get started making our own!

We are going to create a new file called game.directive.js in our app/game folder. Here is that file:

    'use strict';

        .directive('blackjackGame', blackjackGame);

    function blackjackGame(){
        return {
            restrict: 'E',
            templateUrl: 'app/game/game.directive.html',
            controller: 'GameController',
            controllerAs: 'game'

Whatever we call our directive will be what is used in the implementation of it in html. Angular auto converts our camel case “blackjackGame” into “blackjack-game” for usage. There is also a trend (that I’m following in this example) of prefixing your directive with some sort of namespace tactic. Our namespace is ‘blackjack’. Had we called our directive “game” instead, then down the road used some sort of third party directive with the same name, we would’ve had issues. This way eliminates those issues.

The format for the directive method has some complicated options, but we will keep this one reasonably sane. I’ve previously written about the ‘restrict’ option, but just know that ‘E’ will require us to use the element name like so:


The controller and controllerAs replaces the “ng-controller=’GameController as game'” from shell.html. The templateUrl tells angular where to get the html to fill this directive with. game.directive.html looks like so:

 <div ng-if="!game.started">
 <button class="btn btn-primary" ng-click="game.start()">Start Game</button>
 <div ng-if="game.started">
 Game In Progress
 <button class="btn btn-danger" ng-click="game.end()">End Game</button>

Starting to look familiar? We’ve simply ripped this out of the shell.html file. Now our main area in shell.html looks like this:

<div class="primary-area">
 <h1>Welcome to Angular Blackjack</h1>

This makes the main html component easy to read and understand what is happening on the page. There are lots more options for directives, but since this is a very basic one, we won’t configure it any more.

We’ve now created our first custom directive and replaced lots of lines of code in our template with one simple line!

Here is the result of our work

Hope you all are enjoying this series. Please feel free to reach out with any questions or concerns.

Up Next: Services

Angular Project Blackjack: 3 – Unit Testing

(This post is part of my “from scratch” AngularJS project. If you are feeling lost, the first post is here.)

Now that we have our application running and our first controller done, the next thing we want to get setup is our testing framework. Having a testing framework ready to go is always beneficial, no matter what kind of development style you choose. I haven’t been able to get on board with TDD, but that is just my personal preference. I do like to have unit tests that cover my code, but I find it easier to write the tests after the code rather than before.

We are going to use the karma test runner suite to run our jasmine tests. Karma is a tool developed by the AngularJS team to run unit tests against a browser. It has the option to watch files for changes and re-run tests as soon as it detects them. It also reports passes/failures of the tests. Jasmine is the tool that we will write our tests in. We will test each part of the code, expecting certain things to happen, causing the tests to pass or fail.

Let’s get our environment setup to do some testing. Since this is first time we’ll be using npm to install something we want to save to the project, let’s first create a package.json file in the projects root directory:

  "name": "angular-blackjack",
 "version": "0.0.1"

Now we are able to install packages with npm and save them to our package.json file so that they can be installed on any other machine that we take the project to.

npm install karma --save-dev
npm install karma-phantomjs-launcher --save-dev
npm install jasmine-core --save-dev
npm install karma-jasmine --save-dev
bower install angular-mocks --save-dev
karma init karma.config.js

This will initialize our karma test runner file karma.config.js. When it asks for which browser you would like to test on, enter ‘PhantomJS’. This is our “headless” browser that runs nicely on the command line. The most important part right now is to make sure karma is loading all of our source files properly like so:

files: [
//Test Specs

We are telling karma to load all of our javascript files in the src directory, but we want to specifically tell it to load the ‘.spec.js’ files. These will be our tests.

In order to execute tests, inject angular code and core services, we also install angular-mocks. From the documentation, angular-mocks (or ngMocks) “provides support to inject and mock Angular services into unit tests”. This means we do things like “inject”, “dump”, and “module”. Things that are necessary to test our code.

Following the style guide, we want to keep our tests along side of our source code and name the tests as close to the files they are testing as possible. Our first tests will be on our game.controller.js file, so we will put it in the same directory and call it game.controller.spec.js. Let’s go through our test:

describe('GameController Unit Tests', function () {
    var gameController;
    beforeEach(function () {
        inject(function ($controller) {
            gameController = $controller('GameController');

    it('should be true', function () {

    it('should have a start and end function', function () {
        expect(typeof gameController.start).toBe('function');
        expect(typeof gameController.end).toBe('function');

First, our describe() function, well, describes the tests that are run in the second parameter. Everything within beforeEach() function will be executed, I hate to say this, before each test is run. Notice a pattern here? The Jasmine framework makes very readable code. Next, we’ll load our module with the module() function. The inject() function is where things get a bit different. Since we will be creating a controller to test, we will use the $controller service. We’ll create our ‘GameController’ within the inject function, so we have access to the $controller service we just injected. If we were to need the $controller service outside of the inject function, there is another method we could use, but that is (yet another) blog post!

Now that our gameController variable has been defined, we can run some actual tests on it. The first test:


is a good way to reveal any setup issues you may have. If the tests fail, you know you’ve done something wrong. For the next test, we will actually verify that our controller has the ‘start’ and ‘end’ functions available:

it('should have a start and end function', function () {
    expect(typeof gameController.start).toBe('function');
    expect(typeof gameController.end).toBe('function');

These ‘toBeDefined’ functions verify that, yes, these functions are defined on the controller. But, if there was a property called ‘start’, this would validate as true also. That is why we have the ‘typeof’ validation as well.

These tests can be run on the command line with

karma start karma.conf.js

We now have our unit testing framework setup and running a test against our first controller that we wrote. Not a bad start, especially without using any sort of generator or starter template!

One final note. I switched over to WebStorm a few months ago and I couldn’t be happier with the IDE. Coming from a Visual Studio and an XCode background, this IDE makes me feel like home. Here is WebStorm’s visualization of the tests we just wrote, pretty great right!?!

Screenshot 2015-02-11 22.23.42

Here’s the results of our work!

Up next: Making A Directive

Angular Project Blackjack: 2 – Our First Controller

This post is part two of my “from scratch” AngularJS project. If you are feeling lost, the first post is here.

In our last post, we got our project directory setup, loading angular via bower and serving our files locally with http-server. Before we do anything else, let’s make it look somewhat decent via bootstrap. We’ll download it via bower. Then we’ll link the files in our index.html

bower install bootstrap --save

We’ll update the shell.html with with the bootstrap base template taken straight from the docs.

Now that we’re looking half-way decent, we’ll start by putting our game on the page. In AngularJS, our controllers are the ‘C’ to the MVC. They also can be the ‘VM’ in MVVM, depending on how you look at it. I’m a big MVC guy and since the C in MVC stands for ‘Controller’, so I’m just going to go with that. Let’s create our controller for the game, called GameController. As we go along, this will eventually contain the entire game. Since we are just getting started though, the only things our game controller will do right now is to start and end a game. Here is the meat to our controller:

function GameController(){
    var game = this;

    game.init = function () {
        game.started = false;

    game.start = function () {
        game.started = true;

    game.end = function () {
        game.started = false;


I’m setting up this controller to always be used in a ‘controllerAs’ situation. This eliminates the need to use $scope in your controllers, and it is highly suggested by most Angular professionals. I also almost always use an init function in my controllers. I’ve found that it makes testing a bit easier when you want to see how your controller behaves with different variables. It is also good to have all your initialization code easy to find and manage. I’ve seen some controllers with variables being init-ed all over the place and it is tough to follow. Our start and end functions will be called on buttons in the view.

Let’s implement this controller on the view side.

<div ng-controller="GameController as game">
    <div ng-if="!game.started">
        <button class="btn btn-primary" ng-click="game.start()">Start Game</button>
    <div ng-if="game.started">
        Game In Progress
        <button class="btn btn-danger" ng-click="game.end()">End Game</button>

Our view now has two states, game started and game stopped. The ‘ng-if’ displays the proper button for each state. You’ll see we’ve wired up the buttons with ‘ng-click’ to call those functions we defined on the controller.

We’ve got our game controller being displayed and the buttons are functioning properly, so we will leave it here. Take a look at the resulting code here.

One thing to note, I would normally put this game controller into a directive and just throw the directive into shell.html, but since we haven’t discussed directives yet, we’ll leave that for another post!

Up next: Unit Testing!

AngularJS Blackjack Intro – Project Setup

About a year ago, I switched from being a full time iOS developer back to a web develox0ml8per specializing in AngularJS. Luckily, my company took a chance on me and let me learn it on the job. I have been absorbing as much Angular information as possible, trying to make sure I was at the top of my game. I found myself becoming quite skilled and even making a few small demo projects. Until, one day, I realized I didn’t really know how a lot of this worked. There was too much “magic” in the process. Sure, I could use yeoman and get an angular project building and releasing within a few hours, but I had no idea what the back end was actually doing. I felt a lot like our friend over here, not knowing some of the basics of the code. That’s why I decided to start this series of posts on creating an AngularJS project from scratch.

Most of my posts on AngularJS have been some pretty high level looks into specific topics (especially unit testing). In this series of posts, I’m going to be building a small, single-page, blackjack game in AngularJS. This will all be open sourced. We’ll be following some ground rules:

TL;DR: By the end of this post our code base should look like this:

First, let’s get the project folder going:

mkdir blackjack
cd blackjack
bower init
mkdir src src/app

Since we will be using bower, let’s configure it to install the components into our src folder so that they will be accessible from our index.html file.


    'directory': '/src/bower_components'

Next, let’s install angular:

bower install angular --save

We’ll setup our files like so:

As you can see, we’re already starting to use John Papa’s style guide suggestions with the blackjack.module.js filename and the layout folder. Also, the .editorconfig, .jshintrc.gitignore files are all from

We now have our application and angular loading, so let’s load it in a browser! Oh, yea, about that. We’d really like a grunt/gulp serve solution with auto-refreshing fanciness like we get when we use yeoman to generate a project, but that’s for another blog post! We can serve from our src using a nifty node app called http-server

npm install http-server -g
cd src

And so, we’ve hit our commit. We’ve got an angular app serving text. This seems like a good stopping point. Stay tuned for more progress on our game!

Up next: Our First Controller

AngularJS: Testing a Directive’s Controller with Isolate Scope Expressions

When writing unit tests for an AngularJS directive, there’s not a breadth of information online past the ‘basics’. This fact came to me rather quickly when I tried to write a simple unit test titled: “it(‘should call the passed function’…”. I had created a directive which accepted an isolate scope expression passed from the parent controller. Side-note: a good recap on isolate scope is found here. I finally figured it out with a little ‘controllerAs’ magic.

To follow along, open this jsfiddle!

“How did this work and what was I testing?”

myApp.controller('MyDirectiveController', ['$scope',function($scope){
self.doSomething = function (){
//Call the passed expression

This is the entire directive’s controller. My function in the directive’s controller (‘doSomething’) calls the passed expression (‘passedExpression’) from the parent controller. What I was trying to do in my test was verify that when a method in the directive’s controller was called, it was actually calling the function on the parent controller.

The Directive

myApp.directive('myDrtv', function () {
return {
restrict: 'E',
scope: {
passedVar: '=',
passedExpression: '&amp;'
template: '
<div>Hello {{passedVar}}</div>
controller: 'MyDirectiveController',
controllerAs: 'myDirectiveCtrl',
replace: false

view raw


hosted with ❤ by GitHub

So, our directive accepts the passed expression and it gets assigned to the directive’s isolate scope as  “$scope.passedExpression”. My initial thought was to simply test the MyDirectiveController without actually compiling the directive, but that doesn’t give us a full test (and would be way too easy to do!).

“Show Us the Test!”

describe('myApp', function () {
var element, scope, innerScope, elementCtrl;
beforeEach(function () {
//Create Element with our directive
element = angular.element('<my-drtv passed-var="passThis" passed-expression="myFunction()">');
inject(function ($rootScope, $compile) {
scope = $rootScope.$new();
//Create scope variables to pass to the directive
scope.passThis = 'Passing';
scope.myFunction = function(){};
//Now our element is ready and behaving like it would on a page
innerScope = element.isolateScope();
elementCtrl = innerScope.myDirectiveCtrl;
it('says hello', function () {
expect(element.text()).toBe('Hello Passing');
it('should call the passed function', function(){
//Watch our main scope's function
//Tell the element to call it's function that calls the parent's function

view raw


hosted with ❤ by GitHub

The first test verifies that our parent scope’s variable was passed to the directive properly. The next one is what caught me. I could not figure out how to call the “doSomething()” function on the element’s controller. I tried using the ‘$controller’ injection to get to it, but the instance it created was not the same as the element’s controller. Once I started debugging, I started looking at the results of the function “element.isolateScope()“. There was a property on that scope object that was returned “myDirectiveCtrl” that I immediately found out was the directive’s controller instance! After that I could call whatever I wanted on it. With jasmine, I’m spying on my parent scope’s function to make sure it is being called.

I did see that there was an “element.controller()” function, but it never worked properly for me. If it works for you, please let me know!

“Now what?”
Go write some better unit tests! Also, write as many directives as you can! I’ve found that moving code out of my templates and into directives has really helped modularize my projects. Being able to reuse a directive is such a time (and code) saver!

Once again, this example lives on jsfiddle.