AngularJS: One Step at a Time

Michael Crump explains how to get started using AngularJS.

As a web developer, you are always looking for ways to enhance your HTML web apps with the comfort and safety of a framework that won’t disappear overnight. While there have been many frameworks that have come and gone, AngularJS is not one of those. AngularJS is backed by Google and is an MVC framework that allows you to define very powerful templates directly in your HTML and includes data binding and dependency injection which makes your code not only easier to write but for others to read. Let’s take a look at what it takes to get started:

Using AngularJS

You have a couple of options when it comes adding the AngularJS framework to your app:

You can either download a zip file of the framework to your local machine, use the CDN provided on the AngularJS web site or use Bower, which is a package manager for the web.

As of this writing there are two branches:

  1. 1.2.x (legacy) – For those looking for a stable build, that may not need any of the features included in 1.3.x.
  2. 1.3.x (latest build) – For those that live on the cutting edge, updates almost weekly.

For the sake of this demo, we will be using the CDN and the recently released 1.3.x for this demo. We can grab the URL to the CDN by going to the AngularJS web site and selecting the download button and clicking on 1.3.x -> Minified and copy and paste the CDN URL as shown in Figure 1.

Getting Started

Figure 1 : AngularJS Download Selection Screen.

Jump in Feet First!

I’m a big believer that in order to learn something you need to see it in action first, then fill in the gaps as you work your way through a new framework or language. With that being said, now that we know where to get AngularJS, we can use any web editor of our choice or even in-browser clients like Plunker. I personally like to use a desktop web editor for advanced features and usually choose between the following: Sublime Text, Visual Studio, Web Storm, etc. Pick your web editor of choice and create a new file called index.html.

Starting with a completely blank HTML5 page, add the code below:

<!DOCTYPE html>

<html ng-app>

<head>
    <title>Getting Started with Angular from Modern Web</title>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.0-rc.0/angular.min.js"></script>
</head>

<body>

<div>
    21 / 3 = {{21 / 3}}
</div>
<div>
    21 + 3 = {{21 + 3 }}
</div>
<div>
    21 * 3 = {{21 * 3}}
</div>
<div>
    21 - 3 = {{21 - 3}}
</div>  
</body>

</html>

Three things come to mind with this first simple example:

  1. The html tag has ng-app added. This is an example of a directive that auto-bootstraps an AngularJS application.
  2. The script tag has a reference to the CDN link referenced in Figure 1.
  3. The div tags does simple division, multiplication, subtraction and adding, but uses the double curly braces to complete the evaluation. These are called Angular expressions. Don’t get these confused with single curly braces as these are standard objects in JavaScript.

If we run this application, then we will see the following in the browser.

21 / 3 = 7
21 + 3 = 24
21 * 3 = 63
21 - 3 = 18

Angular automatically found the expression tags and performed the calculation without any additional code.

If we remove ng-app as specified in our html tag, then the browser would have displayed the following as it wouldn’t have known that this is an angular app. It would NOT have thrown an error as you might expect.

21 / 3 = {{21 / 3}}
21 + 3 = {{21 + 3 }}
21 * 3 = {{21 * 3}}
21 - 3 = {{21 - 3}}

Moving Beyond Pre-School Math!

Now that we have our feet wet with building our first simple AngularJS app, let’s take a look at using an Angular directive called ng-controller that attaches a controller class to a view. (We used a directive in the first sample called ng-app) This is important to grasp early on as this is how Angular supports the principles behind the MVC pattern.

Take a look at the code shown below:

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

<head>
    <script src="scripts/angular1.3.0-rc.0.js"></script>
    <script src="scripts/script.js"></script>
</head>

<body>

<div ng-controller="MainController">
    {{helloworld}}
    <div>Total Length: {{helloworld.length}}</div>
</div>

</body>

</html>

Very similar code to the first example, except ng-app now has a name associated with it simply called “app”. We’ve also added another script called script.js (which we will talk about shortly). Inside of our first div statement, we use ng-controller (as explained earlier) and give it a name of MainController. We setup two Angular expressions that are going to display a word and provide its total length.

Looking at the script.js file

(function(angular) {

    function MainController($scope) {
        $scope.helloworld = "Hello, Modernweb Developer!";
    }

    angular.module("app", []).controller("MainController", ["$scope", MainController]);

})(angular);

We are going to put this in a self invoked anonymous function, and create a function called MainController passing in $scope. This is an important concept as a scope is an object that refers to the application model. We declare the helloworld value inside this function as well. We finish up by creating an angular module and add MainController as a controller that our Angular app can understand.

If we run this application, then the following will be shown in the browser:

Hello, Modernweb Developer!

Total Length: 27

As expected, it returns the helloworld value from our MainController and gives us a total length of the string.

What would happen if we removed ng-app in this application?

The following is displayed in the browser, but again no error messages in the developer tools as the page is not identified as an Angular app:

{{helloworld}}
Total Length: {{helloword.length}} 

Lets introduce an error

Leaving the app registered as an Angular app, lets create a typo in the div tag for MainController. We will give it a name of Maintrollerr (with an extra r). The web page will load with the code shown above, but this time it will include an error if you look at the developer tools as shown below:

Error: [ng:areq] Argument 'MainControllerr' is not a function, got undefined

Moving a Step Closer to a Real-World Application

We’ve taken a few steps so far, to understand how to manipulate our web app and see how it behaves with different errors, but real-world applications usually need some way to perform CRUD operations. For the purposes of this article, I searched the web for one that wouldn’t complain about CORS or require you to sign up for an API key. The result was GitHub.

We will leave all the code that we had before except remove everything between the body tags and replace it with the following code.

<body>

<div ng-controller="MainController">
    <h1>GitHub API User Lookup Sample</h1>

    <div>{{error}}</div>

    <form name="searchUser" ng-submit="search(username)">

        <input type="search" required placeholder="Lookup user" ng-model="username" />
        <input type="submit" value="Search">

    </form>

    <div>
        <div><img ng-src="{{user.avatar_url}}"></div>
        <div ng-show="user.name">{{user.name}}</div>
        <div ng-show="user.html_url"><a ng-href="{{user.html_url}}">User Profile</a></div>
    </div>

</div>
</body>

We’ve added a div that includes an error message and a simple form that uses ng-submit passing in a function called search with the username parameter. The input type for search uses ng-model and defines the name as username. Inside the div statement, we are going to display an image as well as text and a URL that maps to a GitHub user’s profile. ng-show has been added to a couple of the div tags to only display them if data is present. The GitHub Api of a user simply returns a JSON object. An example can be found here

We will modify our script.js to look like the following:

(function(angular) {
    function MainController($scope, $http) {

        var onUserComplete = function(response){
            $scope.user = response.data;
        };

        var onError = function(reason){
            $scope.error = "Could not reach the server!";
        };

        $scope.search = function(username){
            $http.get("https://api.github.com/users/" + username)
                .then(onUserComplete, onError);
        };
    }

    angular.module("app", []).controller("MainController", ["$scope", "$http", MainController]);

})(angular);

Here you can see that we added $http to our MainController function as well as the module. We also added three functions including the function to lookup a username based upon what the user typed into the form. If an error occurs, then it will simply display a message informing the user of the situation. Otherwise, it will return the data to $scope.user.

Run the App!

As shown in Figure 2, once the user types a name and hits the submit button then it will read the JSON for the current username and return the results to our webpage.

Final Result

Figure 2 : AngularJS App Displaying Public Info From the GitHub API.

Wrap-Up

Hopefully this article has given you a taste of what AngularJS has to offer. I’d like to wrap this article up with some resources where you can evaluate whether it is right for you and/or your organization.

  1. Learn-Angular.org has free interactive lessons that walk you through step by step building a simple app. You can write all of your code in the browser and it covers directives, services and enriching applications.
  2. Introduction to Angular.js in 50 Examples is my personal favorite video on the topic as Curran Kelleher starts from the basics and builds his way up. So far, I’ve only found Part 1 of this video, but it includes 36 of the 50 examples. He also has posted the code to all 50 examples on Github.
  3. A JavaScript Feed Reader in Under 10 Minutes Using Angular JS by Jeremy Likness shows how to build a feed reader in under 10 minutes. I found this video most helpful as he actually shows you how to build a fully-functional app instead of several smaller demos.
  4. The AngularJS Cheat Sheet is a valuable resource to print out and have by your side as you start working through AngularJS samples. It is one of the oldest resources on my short list, but it was last updated on May 1st, 2014 as of this writing. I’ve noticed that the author keeps it current.
  5. Using Kendo with AngularJS – With the popularity of Kendo UI, many folks don’t know that it can be used with AngularJS. This page helps new Angular developers learn how to integrate it quickly and easily.

Thanks for reading and feel free to reach out to me anytime on Twitter at @mbcrump or my personal blog at michaelcrump.net.

Header image courtesy of David McAughtrey

Previous

Modern Web Best Practice: Build Tools

Modern Web Best Practice: Testing

Next

6 thoughts on “AngularJS: One Step at a Time”

    • I don’t think one should dismiss a technology because one is easier to use over another. I think you should evaluate both and use what is best for your project.

Comments are closed.