AngularJS: Difference between Service vs Provider vs Factory

If you are searching for this it’s probably because you are trying to figure out which one is the right one for you to use. Or because you’ve come across the three of them and are trying to determine the difference because they seem similar.

If you think they are similar – you’re right. They are very similar. In fact, they are all the the same thing.

They are all providers. The factory and the service are just special cases of the provider, but you can accomplish everything you want using just provider. I’ll show you.

[Read more…]

AngularJS Game Programming: Making Minesweeper (Part VI)

angularjs-game-programming-making-minesweeper-blog-part-vi

Last time on “AngularJS Game Programming”: We added numbers to our minefield! Now a player can figure out where the mines are. In this post were going to keep track whether the player has won and notify them.

Win or Lose

We now have a complete minesweeper minefield. But it’s not a game until you can win or lose. Let’s add the code that checks for that. But first, let’s clearly define what it means to win.

A player wins when they uncover all the safe spots. Said another way, a player wins when the only uncovered spots left on the minefield all contain mines. If an uncovered spot contains anything other than a mine they haven’t won yet.

function hasWon(minefield) {
    for(var y = 0; y < 9; y++) {
        for(var x = 0; x < 9; x++) {
            var spot = getSpot(minefield, y, x);
            if(spot.isCovered && spot.content != "mine") {
                return false;
            }
        }
    }
    
    return true;
}

We need to check whether the player has won each time they uncover a block. To do that let’s change the ngClick we have on the td to call a function instead of what it is now spot.isCovered = false. That way we can easily add this additional logic.

Create a function called uncoverSpot() and move the current ngClick code there. Unlike our other functions this function has to be in the scope so that it can be called from the view.

So replace the code in the ngClick with ng-click="uncoverSpot(spot)", it should look like this:

<td ng-repeat="spot in row.spots" ng-click="uncoverSpot(spot)">

Update the controller to add this:

$scope.uncoverSpot = function(spot) {
    spot.isCovered = false;
};

Add the check to see if they won after the setting isCovered. If they win track it in a variable so that we can display a message to the user. Like this:

if(hasWon($scope.minefield)) {
    $scope.isWinMessageVisible = true;
}

Add the message to the HTML:

<h3 ng-if="isWinMessageVisible">You won!</h3>

Play with it at: http://jsfiddle.net/luisperezphd/UWSWy/

Next Time

In the next post we’re going to add the ability to add “lose” detection.

Part 7: Lose Detection