koajs – Your AngularJS application using the KAMN stack – part 2/2

Introduction

So you have completed part 1 of this tutorial and are now eager to know how to write an awesome frontend for it. Well, good news: In this tutorial I will give you a crash course in AngularJS which is Google’s interpretation of a MVVM (Model View ViewModel) / MVC (Model View Controller) framework.

Agenda

  • Prerequisites
  • Downloading and installing AngularJS
    • Option A: Locally hosted AngularJS (downloaded from Google)
    • Option B: CDN hosted AngularJS (hosted by google, recommended for production)
  • Hello AngularJS
  • Connecting AngularJS to your REST api

Prerequisites

Create a folder on your desktop and call it kamn-angular. Inside this folder put the following folder structure:

  • kamn-angular
    • js
    • css (optional)
    • assets (optional)
    • index.html (empty file for now)

Open the index.html file in your favorite text editor and create an empty standard html document:

index.html:

<!doctype html>
<html>
    <head>
        <title>My first angularJS app</title>
        <meta charset="utf-8">
    </head>
    <body>
    </body>
</html>

Downloading and installing AngularJS

You can download AngularJS directly from Google or use it via a content-delivery-network (CDN).

Option A: Locally hosted AngularJS (downloaded from Google)

Depending on your custom settings you made while downloading AngularJS you will have either a minified or an uncrompressed version of AngularJS. For development purposes I recommend using the uncompressed version. Inside your downloads folder you will have a angular.js file. Copy that file to YOUR_DESKTOP/kamn-angular/js/angular.js.

Now in your index.html add the following script tag to your body:

<script type="text/javascript" src="js/angular.js"></script>

Option B: CDN hosted AngularJS (hosted by google, recommended for production)

If you want to use CDN hosted AngularJS simply drop the link to it inside your html body:

<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>

Check out Google’s CDN for more versions.

You might wonder why there is no http:// or https:// in front of the URL. That’s because it’s a protocol relative URL populated by Paul Irish.

Hello AngularJS

Now that we have linked the AngularJS library inside our html document we’ll now write our very first AngularJS module. Head over to YOUR_DESKTOP/kamn-angular/js and create a new file called app.js:

js/app.js:

var app = angular.module("kamn",[]);

app.controller("KamnCtrl", ["$scope", function($scope) {
    $scope.message = "Hello AngularJS";
}]);

Okay – what happened here? Let me explain:

Line 1: First up, we created a new angular module called “kamn”. The second argument of angular.module takes a an array with dependencies which our module would need. Since our module has no dependencies we just pass an empty array.

Line 3: We create a KamnCtrl for our module. The controller needs a $scope which is injected.
Note: We could just pass a function like function($scope) { } which would just work fine until we minify our project. We therefore pass any dependencies as a string in array form as explained by the AngularJS team:

Since Angular infers the controller's dependencies from the names of arguments to the controller's constructor function, if you were to minify the JavaScript code for [KamnCtrl] controller, all of its function arguments would be minified as well, and the dependency injector would not be able to identify services correctly.

We can overcome this problem by annotating the function with the names of the dependencies, provided as strings, which will not get minified.

Line 4: We set a new property message to “Hello AngularJS” to the $scope object. The $scope object can later be directly accessed in out template.

Next up we would want to connect our AngularJS controller to our HTML file. A few steps are required:

1. Add app.js as a script to your HTML inside the body tag, underneath angular.js:

<script type="text/javascript" src="js/app.js"></script>

2. Define which module your template uses. Modify the html tag:

<!doctype html>
<html ng-app="kamn">
...

3. Define a div which will act as the controllers scope:

<div ng-controller="KamnCtrl"></div>

4. Output $scope.message:

<div ng-controller="KamnCtrl">{{message}}</div>

You’re done. The complete HTML file should now look like this:

index.html:

<!doctype html>
<html ng-app="kamn">
    <head>
        <title>My first angularJS app</title>
        <meta charset="utf-8">
    </head>
    <body>
        <div ng-controller="KamnCtrl">
            {{message}}
        </div>
        <script type="text/javascript" src="js/angular.js"></script>
        <script type="text/javascript" src="js/app.js"></script>
    </body>
</html>

If you now open index.html in a browser “Hello AngularJS” should be displayed. I also created a JSFiddle containing the example if you encounter any problems.

Note: AngularJS uses two way data binding. You could use an input field with ng-model to modify a value on-the-fly. Check out this JSFiddle for a simple example.

Connecting AngularJS to your REST api

For this part of our little AngularJS application, I assume that you have completed part 1 of this tutorial or have a REST api running which responds to /users and returns an array.

Let’s modify our controller and add a function to fetch the users from the db:

js/app.js:

var app = angular.module("kamn",[]);

// Add new service $http
app.controller("KamnCtrl", ["$scope", "$http", function($scope, $http) {
    // Hello AngularJS message
    $scope.message = "Hello AngularJS";

    // Initialize empty user array
    $scope.users = [];

    // Define fetcher for users
    $scope.getUsers = $http.get("/users").then(function(users) { 
        $scope.users = users;
    }, function(err) {
        console.error(err);
    });

    // Call it!
    $scope.getUsers();

}]);

First we add a new dependency for the $http service to our controller. Then we initialize an empty array which will later contain our users.

We then define a fetcher for our users which uses the $http.get method which will return a Promise. On success we set $scope.users to our newly fetched data and on error we log the error in the console.

Optional: refresh button

You could add a refresh button to index.html. You would have to add the following HTML snippet to your controller scoped div:

<button ng-click="getUsers()">Refresh user list</button>

To iterate over the users and display all of them we use ng-repeat:

<p ng-repeat="user in users">{{user.firstname}} {{user.lastname}}</p>

I think it’s pretty much self-explanatory.

Your complete HTML file would now look like this:

index.html:

<!doctype html>
<html ng-app="kamn">
    <head>
        <title>My first angularJS app</title>
        <meta charset="utf-8">
    </head>
    <body>
        <div ng-controller="KamnCtrl">
            {{message}}
            <p ng-repeat="user in users">{{user.firstname}} {{user.lastname}}</p>
            <button ng-click="getUsers()">Refresh users</button>
        </div>
        <script type="text/javascript" src="js/angular.js"></script>
        <script type="text/javascript" src="js/app.js"></script>
    </body>
</html>

That’s it! You have successfully connected your very first AngularJS application to your REST api.

If you want to learn more about AngularJS be sure to check out this great book:

AngularJS - Up & Running from O'REILLY
Source: amazon.com

Like what you read? – Donate

Trackbacks

Leave a Reply

Your email address will not be published. Required fields are marked *