Off the Ridge Code Newsletter


How to Angular – Part 6 – Routing in AngularJS

Published May 18, 2015 in AngularJS - 1Comments

Routing in AngularJS

In this post, I’m going to talk a little bit about routing in AngularJS and add a new route to our existing application. As a reminder: This is a sample application that we’ve been creating since Part 1 of How to Angular. The current version runs inside WebStorm. If you don’t own a copy of WebStorm, I highly encourage you to download a 30 day trial.

Why do we need Routing in AngularJS?:

As the application grows, we may to need to provide multiple views and send the user to a different page with details. AngularJS is a SPA (Single Page Application) centric framework and such all the calls to the server should be done for the purpose of retrieving data or messaging. Therefore, we need to map each http request or route to a particular view. This will logically divide our SPA into parts and keep it maintainable. Notice that each ‘view’ is actually a partial view a not a full html page.

Steps to add routing to the existing application:

Step 1.

Open app.js file and modify as follows:

var app = angular.module('myfirstangularapp', ['ngRoute']).

      $routeProvider.otherwise({redirectTo: '/view'});
We injected a dependency on the ngRoute module which includes the $route service and will provide routing services for our application.
In turn, the $route service includes the $routeProvider that is used to configure the routes.

There are two methods on the $routeProvider:

1. when(path, route) – takes the path that is matched against $location.path and route that will be assigned to $route.current.

2. otherwise(params) – executes if no route definition is matched.

Step 2.

1. Create a ‘templates’ directory under the ‘app’ directory.
2. Create the view.html file under the ‘templates’ directory.


Step 3.

Cut out the entire code fragment between

<div class="container"></div> 
out of index.html and paste it inside the view.html file under the templates directory.

Step 4.

Remove the ‘ng-controller=”MyFirstController”‘ directive from the div inside the index.html page.

Step 5.

Add ng-view directive to index.html. It basically replaces the fragment of that html that you’ve removed in step 3 as follows:

  <div class="container">

ngView is a directive that complements the $route service by including the rendered template of the current route into the main layout (index.html) file.

After you perform Steps 3 and 5. This is what your View.html partial page should look like:

    <p class="text-muted">
        1. Lower case filter:</p>
    <p class="text-info">First Name : {{data.firstName | lowercase}}</p>
    <hr />
    <p class="text-muted">
        2. Upper case filter</p>
    <p class="text-info">First Name : {{data.firstName | uppercase }}</p>
    <hr />
    <p class="text-muted">
        3. Date filter: (mm)</p>
    <p class="text-info">Start Month : {{data.startDate | date:'MM'}}
    <hr />
    <p class="text-muted">
        4. Custom filter to remove all spaces:
    <p class="text-info">{{data.dashes | removeAllSpaces}}</p>
    <hr />
        <img ng-src="{{getGravatar(}}" />
        <label>Github return code:
            <h4 ng-bind="status"></h4>
        <pre>{{user | json}}

This is what your index.html partial page should look like:

<!DOCTYPE html>
<html ng-app="myfirstangularapp">

    <meta charset="utf-8"/>
    <title>AngularJS - Sebastian Brukalo</title>
    <link data-require="bootstrap@*" data-semver="3.3.2" rel="stylesheet"
    <script data-require="bootstrap@*" data-semver="3.3.2"
    <link rel="stylesheet" href="style.css"/>

<div class="container">

<script src=""></script>
<script src=""></script>
<script src=""></script>
<script src="app/app.js"></script>
<script src="app/controllers/controllers.js"></script>
<script src="app/filters/filters.js"></script>
<script src="app/services/services.js"></script>
<script src="app/directives/directives.js"></script>

Step 6.

Notice that I’ve added an angular-route.min.js library reference to the index.html page. The reason is that ngRoute is not included inside the angular.min.js library.

If we’ve done everything correctly, then, the application should still work and function as before with the difference that now the main view is encapsulated into its own partial view.

Full code example in WebStorm.

Happy coding!

How to AngularJS – Part 5 – Built-in Directives and custom Directives

Published May 4, 2015 in AngularJS - 0Comments

In this post I’d like to talk about directives, both built-in directives that ship as part of AngularJS as well as how to create your own custom directives.

So, what are directives in AngularJS:

Directives in AngularJS, in short, are a way to teach HTML new tricks, they are markers on DOM elements. For example: The way we make data show on the screen is through the use of binding expressions  {{  }} which is a type of Data binding directive.

However there are many other directives that ship with AngularJS, some of which you’ve already seen:

  • ngController
  • ngApp
  • ngBind
  • ngClick

and, many others, The full list can be found here: AngularJS API

There are 4 ways that directives can be applied.

1. As a tag form: <ng-bind>

2. As an attribute: <div ng-bind>

3. As a class: <div class=”ng-bind”>

4. As an HTML Comment.

Let’s look at ngModel and ngClick, and how we can incorporate those into our application.

Step by Step:

1.First, I’m going to turn the JavaScript function expression into an AngularJS function on the scope.

i.e. this:

var getGitHubUser = function(username) {
         gitHubUserLookup.lookupUser(username).then(onLookupComplete, onError);
$scope.getGitHubUser = function(username) {
        gitHubUserLookup.lookupUser(username).then(onLookupComplete, onError);
and remove the explicit call inside the MyFirstController.js to getGitHubUser(userData.user.username);

2. We’re going to allow the user to type in a user name they wish to lookup. We’ve already removed the ‘automatic’ call to the getGitHubUser(…) function; now, we’re going to add a text input box and button click.
The text input box will have the ngModel directive associated with it.
ngModel directive binds input controls to a property on the scope or, in other words binds our view to the model.

Notice the dash inside the ng-model directive. Directives inside the AngularJS source code are defined using camelCase i.e. in this case ngModel. However, when we use them inside the HTML we need to use spinal-case. i.e. ng-model; hence, ngModel and ng-model refer to the same thing.

<a name="userinputwithclick"></a>
 <label>User:<input type="text" /></label>

These are all the changes required to enable the user to type in and lookup any user they wish to. No custom JavaScript or jQuery is necessary to grab the user name and execute the call. This is the AngularJS way!

Now, let’s see how we can write a custom directive and create a custom element.

I’m going to turn our input box and button click into a directive.

Step by Step:

1. I’m going create a new file called directives.js. To register a custom directive with AngularJS we use a keyword: ‘module.directive‘. It’s very similar to how we registered custom filters.
We pass a name of the directive as a first parameter. What we need to return from the directive is a directive definition object.

I’m going to replace the entire markup inside the index.html page:

  <div><label>User: <input type="text" /></label>

with a single element directive .

Custom directive

I’m going to use the ‘template’ property here:

app.directive('myInput', function() {

    return {
      restrict: 'E',
       template: "<label>User:<input type="text" /></label><button>GO</button>"

The restrict ‘E’ means that we are using this directive as an element.

That’s all, everything should work as before.

Looking up AngularJS team in Github

Full example and happy coding!


How to Angular – Part 4.5 – How to use AngularJS Asynchronous Http service.

Published April 24, 2015 in AngularJS - 0Comments

In Part 4.5 I’ll talk about

AngularJS Asynchronous Http service.

In part 4 of ‘How to Angular,’ I presented services and how to retrieve a photo from the service. But, what if you wanted to use a service to retrieve remote data, in JSON, asynchronously? Have no fear, the $http.get service facilities server communication using XMLHttpRequest object.

Briefly, $http service returns a promise which can be used to call the ‘.then’ method and register your own callbacks.
In other words, your own callbacks will be called once the asynchronous call via $http.get returns – whether successfully or not.

To illustrate this I’m going to call the GitHub API service at and retrieve a user for the AngularJS team; the full url call will be:”.

1. The first thing I’m going to do is create a new service called: ‘gitHubUserLookup’

app.factory('gitHubUserLookup', function($http) {
        return {
                lookupUser: function(user) {
                return $http.get("" + user)
                            .then(function(response) {
                             return response;
              // error handler
              function(response) {
                      return response;

2. Then I’m going to inject it (via dependency injection) into our controller:

var MyFirstController = function($scope, $http, userData, userGravatar, <strong>gitHubUserLookup</strong>){...}

3. Next, I’m going to add a function inside the controller that will call into our service:

var getGitHubUser = function(username) {

           gitHubUserLookup.lookupUser(username).then(onLookupComplete, onError);

As I’ve mentioned, the $http service returns a promise on which we can call ‘.then’ method and pass in two callbacks, one for the ‘success’ method and the other for the ‘error’ method.

The onLookupComplete will get called once the request successfully completes:

 var onLookupComplete = function(response) {
          $scope.user =;
          $scope.status = response.status;

5. Finally I’m going to display the retrieved data back on our page:
     <div>Github lookup status: {{status}}</div>
       <pre>{{user | json}}

If there are any errors, then, they will be displayed as well.

Code Example

– Happy coding!

– Sebastian

How to Angular – Part 4 – AngularJS Services

Published April 22, 2015 in AngularJS - 0Comments

In Part 4 of How to AngularJS, I’ll talk about what AngularJS services are, how to use built-in $http service, and how to create your own services.

AngularJS Services can have multiple meanings, they can:

1. Call an external service over the network/wire such as a restful service.
2. Call internally inside the app to retrieve data.
3. …be a worker object that is often stateless.

Angular ships with a lot of built-in services (all Angular services are prefixed with a $ dollar sign), such as $scope or $http service.

Why would you use services? The simple and short answer is: Reusability. If you have a task that you’re repeating over and over it’s probably a good idea to wrap it inside the service. You can package that reusable logic into a container that you can use in different places through the application. It’s also a great way to share data between different controllers. Services can also help you to adhere to the single responsibility principle.

I’m going to move the hardcoded data from the controller I’ve created in How to Angular Post #3 and create a service out of it:

Currently the existing code inside the MyFirstController.js looks like this:

var MyFirstController = function($scope, $http) {
    var userData = {
    firstName: 'Sebastian',
    lastName: 'Brukalo',
    languages: ["C#", "JavaScript", "C++", "Other Web Stuff"],
    email: "",
    startDate: new Date(2000, 02, 04), // month value is 0 based, others are 1 based.
    dashes: 'something that should not have spaces'</p>

    $ = userData;

1. The first thing that I’m going to do is to create a services.js file – that will hold my new service.

I’m going to move the user data i.e. [code]]czoxOTpcInZhciB1c2VyRGF0YT17Li4uLn1cIjt7WyYqJl19[[/code] to my new services.js file.

The way you create and register a service with angular is to call the factory method on the module that we’ve created previously, i.e.

 app.factory('userData', function(){
  return {
         // some code here
Now, combining the two above, results in a service that will provide userData back to our application:

 app.factory('userData', function() {
    return {
        <p style="margin-left: 170px; margin-top: -23px;">userData: {
        firstName: 'Sebastian',
        lastName: 'Brukalo',
        languages: ["C#", "JavaScript", "C++", "Other Web Stuff"],
        email: "Sebastian at Brukalo dot com",
        startDate: new Date(2000, 02, 04), // month value is 0 based, others are 1 based.
        dashes: 'something that should not have spaces'

Notice that I changed from

userData = {..}
to use property 
userData: {..}, 
that’s because we need to create a property that will be returned from that service.

2. There are a couple of things left to do in order to use our new service:

a. In the controller function we need to instruct Angular to inject our new service:

var MyFirstController = function($scope, $http, <strong>userData</strong>){...};

Notice that our service does not have the dollar sign in front of it. Only services provided by Angular use this special convention. If you were to try to create a service with a $ in front, then, you might end up accidentally overriding an existing Angular service.

b. We also need to place the data back onto the $scope:

$ = userData.user;

c. Finally, in our index.html page, we need to register the new script:

<script src="services.js"></script>

Everything should be working as it was before; the difference, of course, is that now we’re calling and retrieving data from the service.

Now, let’s take this one step further and create a real webservice call to retrieve an image from the service. urls are based on the hashed value of an email address.

I’m going to add another service to the services.js file called ‘userGravatar;’ it will have a method called getGravatar that takes an email address as the parameter:

 app.factory('userGravatar', function () {
       return {
              getGravatar: function(email)

In my MyFirstController.js, we’ll assign a function call and bind it to $scope on the getGravatarUrl property:

 $scope.getGravatarUrl = function(email) {
          return userGravatar.getGravatar(email);

In my index.html page, I will call the getGravatar method and pass in my email address:

Now you should see an image below when the service call retrieves an avatar based on the hash of my email address. One other thing to note is the <ng-src> directive – the purpose of it is for Angular to wait until the path is fully resolved.

Happy coding!
Here’s a code example.

How to Angular – Part 3 – Filters in AngularJS

Published April 20, 2015 in AngularJS - 0Comments

Filters in AngularJS

In part 3 of How to Angular, I’d like to present built-in Filters and how to create custom filters.

Code example in Plunker.

I will also make a switch from JSFiddler to Plunker for my code examples. I feel that Plunker is better suited for Angular and for examples that are larger in scope.

I also reorganized the code a bit:

1. The main app is being bootstrapped from app.js file

2. The controller is in its own file MyFirstController.js

– What are Filters in AngularJS?

Filters in AngularJS format the values for presentation to the user but they do not alter in any way the underlying data.

Built-in Filters in AngularJS

AngularJS comes with a lot of built-in filters  and the way to use them:

<strong>{{data | filter}}</strong>
for instance, if I were to uppercase or lowercase all letters in a string I might write:

{{data.firstName | lowercase}}

or, if I wanted to display just the month from a date object I might write:

{{data.startDate | date:'MM'}}

What about a filter that does not exist? This is what the custom filters are for.

– Creating Custom Filters

To create a custom filter you simply register the filter with the module:

app.filter('filterName', function(){

// your filter


for example, let’s write a trivial filter that removes all spaces from a string:

app.filter('removeAllSpaces', function () {
     return function(str) {
            return str.replace(/\s/g, '');

For a full example see my code sample.

Happy coding!

-Sebastian & Free Blogging course

Published April 11, 2015 in Uncategorized - 5Comments –

could be best described as an ‘everyday developer manual’ or, better yet, a ‘how to succeed as a developer’ book. John Sonmez is a teacher, speaker, and the author of “ Soft Skills: The software developer’s life manual,” in which he talks about “soft skills” – a developer’s career, productivity, fitness, investing, as well as marketing oneself. John, as he puts it on his blog, is passionate about “taking the complex and making it simple.”

John compares a developer who writes code to a blacksmith setting up shop in a medieval town. He urges developers to think of their employer as a customer; this promotes an attitude of working for oneself in order to attain a better result, and not simply acting as a drone in a 9-5 job.

Simply put, the topics presented in this book are worth their weight in gold.

John is very successful at what he does; he regularly blogs at where he gets over 3,000 views a day, and offers to help other developers create blogs. When I saw a free email course on “How to boost your career,” I immediately signed up. After all, it is free. All you have to do is provide John with your email address. In return, you will receive  bi-weekly emails on how to get started with hosting and installing your own wordpress blog. There are also lessons followed by ‘homework.’ Yes, you need to do some work. After all, John won’t be writing your blog posts for you but he’ll be there twice a week to remind you how much you’ve been slacking off! Ok, perhaps he won’t call you a slacker but he’ll insist that you work hard and will offer his priceless guidance to help you create your own successful blog.

I highly recommend that you, at the minumum, give some thought to it and check out his free course at

How to Angular – Part 2 – Controllers in AngularJS

Published April 4, 2015 in AngularJS - 0Comments

Controllers in AngularJS

In the last post I’ve showed you how to create a ‘Hello World’ type of application in Angular. Now I’m going to introduce you to controllers and MVC.

Let’s start with defining MVC and what it is: MVC is an architectural pattern and it applies a principle of separation of concerns. In short, it divides our application into:

1. model – holds all of our data.

2. view – presents data to the user (our HTML page) and is in no way tied to the model. In other words, controller talks to the $scope object and never to the view.

3. controller – keeps view and model separated and is in charge of a particular area in our application. Controller is invoked by the Angular framework and builds up the model.

Screen Shot 2015-04-04 at 1.20.12 PM

The $scope object is supplied to our controller function by the Angular during controller invocation. By the way, anything with $ (dollar sign) in front is owned by the Angular framework.

<ng-controller> directive needs to be somewhere inside <ng-app> directive, and remember you can only have one <ng-app> per page, but many <ng-controller> directives (i.e. controllers.)

Before we can create a controller we need to create a module for our application. Then, we can create a controller and finally our model. Hence, there are 3 distinct steps when creating a module and registering controller:

1. Create a module:

var app = angular.module(‘myfirstangularapp’, []);

The first parameter is the name of our application, and the second parameter is an array of dependencies. (we don’t have any yet.)

2. Register controller with the module.

app.controller(“MyFirstController”, [“$scope”, MyFirstController]);

3. Instruct Angular to use our module.

<body ng-app=”myfirstangularapp”>

Now all that’s left is to create our controller function “MyFirstController”:

var MyFirstController = function ($scope) {


So how do we create a model?

We simply attach, or, in other words, assign properties to the $scope object and they become our model. e.g. $scope.myproperty or $scope.mycomplexobject.

var MyFirstController = function ($scope) {
$scope.ManyHellos = [‘Hello’, ‘Hola’, ‘Bonjour’, ‘Guten Tag’, ‘Ciao’, ‘Namaste’, ‘Yiasou’];

Here’s a complete example in JSFiddle:

(please not that <body ng-app=”myfirstangularapp”> is placed under ‘Fiddle Options’ Body Tag. I couldn’t get JSFiddle to work otherwise)

I hope you’ve enjoyed this post and, as always, please send me your comments and suggestions.


How to AngularJS – Part 1 – Introduction to AngularJS

Published April 3, 2015 in AngularJS - 3Comments

Introduction to AngularJS

In the coming weeks I’ll be presenting a series of ‘How to AngularJS’ posts. It’ll be primarily aimed at the novice or beginner audience. (at least in the beginning, no pun intended) :)

First thing’s first: What is AngularJS?

In short, AngularJS is a JavaScript framework to build applications that can run in a web browser.

It started as a Google project but right now it is an open source project that you can contribute to as well.

We are going to write a ‘Hello World’ type of application in AngularJS, so let’s get started.

1. Head on over to and download and click on that big blue button in the middle of the screen.

Download AngularJS

I happen to be writing this blog post on my Mac and so I’ve created a folder under ‘Documents’

2. Create a folder somewhere on your computer. (e.g. C:\HowToAngular\)

 ▸ Documents\HowToAngular\

a. Create a subfolder called ‘js’ (e.g. C:\HowToAngular\js\)

b. Click the download button on the page, select ‘Stable‘ under Branch and Minified under Build and click download. (At the time of this writing I downloaded version 1.3.x (stable))

Download Angular2

c. Save the file (angular.min.js) to the ‘js’ folder (e.g. C:\HowToAngular\js\angular.min.js)

3. Open your favorite text editor. I use Sublime Text editor. It is easy to use, provides color themes and it is pretty darn fast. I have no affiliation with Sublime Text and you’re welcome to use any HTML editor your heart desires. As a matter of fact, you can use Notepad for this example.

The bare minimum we need to insert into our HTML page for AngularJS is:
a. <script src=”angular.js”></script> – a <script> tag pointing to AngularJS file (angular.js)
b. <ng-app> attribute – it is a directive and that is how AngularJS extends HTML. By the way, ‘ng’ stands for Angular.

4. Create an HTML file with the following:

<!DOCTYPE html>


<script src="js\angular.min.js"></script>

<h1>Hello AngularJS!</h1>

<p>Under Angular control: </p>
<div ng-app>
{{ 'Hello ' + 'AngularJS!' }}


<label>Hello: </label>
<input ng-model="hello" type="text" />


<p> <b>Not</b> under angular control </p>
{{ 'Hello' + 'AngularJS!' }}



Notice the <div ng-app> directive that I’ve placed. I could have added the <ng-app> directive to the <html> element and it would have worked just fine; but, you can only have one <ng-app> per page.

The difference of course, is that the first expression renders correctly since it’s under Angular control. The second expression isn’t under Angular control and hence outputs as-is.
I just showed you the bare minimum you need to get started with AngularJS.

Now let’s add one more directive <ng-model>  which binds in this case <input> element to $scope (more on that in future posts) and creates two-way binding – which is the strength of AngularJS.

I’m going to add the following inside our first <div ng-app>

<p style="padding-left: 30px;"><label>Hello: </label>
<input> <strong>ng-model</strong>="hello" type="text" />

Final output

If you run the page now, you should see the above, and typing anything inside the text box will ‘magically’ output it below with no additional (javascript) code.

Here’s the complete listing:

<!DOCTYPE html>


<script src=”js\angular.min.js”></script>

<h1>Hello AngularJS!</h1>

<p>Under Angular control: </p>
<div ng-app>
{{ ‘Hello ‘ + ‘AngularJS!’ }}


<label>Hello: </label>
<input ng-model=”hello” type=”text” />


<p> <b>Not</b> under angular control </p>
{{ ‘Hello’ + ‘AngularJS!’ }}




I hope you’ve enjoyed getting your feet wet with AngularJS. I know I did!

Please send me comments and questions and stay tuned for my posts on AngularJS.


jQuery – Pro Tip #4 – jQuery Difference between find and filter

Published January 26, 2015 in jQuery - 1Comments

jQuery Difference between find and filter

If I have a list of items such as:

<ul id=”tasks”>
    <li class=”task”>Do some work</li>
    <li class=”task”>Do more work</li>
    <li class=”relax”>Relax!</li>

and I’d like to select all list elements inside with class=”task” assigned.

I might want to do something like this:

// cache the result.
var $tasks = $(‘#tasks li’);

var $task = $tasks.find(‘.task’);

and that of course won’t work. The reason is this:

Get the descendants of each element in the current set of matched elements, filtered by a selector, jQuery object, or element.

in other words it says: ‘search through all the child elements only’ and since we are already at the <li> level there’s nothing below it!

The solution to this is to use .filter() method that works on the currently matched elements.

var $task2 = $tasks.filter(‘.task’);

jsFiddle example:

1 2 3