AngularJS 1.x Fundamentals (Part 1)

Getting started with AngularJs fundamentals, features, features and bootstrapping.

Free Course

Getting Started with Angular 2

Angular 2 is the shiny new framework that comes with a lot of new concepts. Learn all the great new features.

AngularJS is a structural framework for dynamic web apps. It lets you extend HTML's syntax to express your application's components in a clear and concise manner.

AngularJS is what HTML would have been, had it been designed for applications. It attempts to minimize the mismatch between document centric HTML and what an application needs by creating new HTML constructs.

AngularJS teaches the browser new syntax through constructs called directives. With the AngularJS framework you can build a versatile application using custom declarative elements with basic application features done for you out of the box.

In this tutorial, I will be introducing you to this superheroic framework and giving you the necessary skills and superpowers you need to make the world a better place with awesome applications.


Should I learn Angular 1.x or Angular 2

There is a lot of debate on which of the two Angular versions a beginner should learn. Many of the arguments are opinionated based on personal preferences or experiences, so I am not going to add to the list of opinions but try to shed some light on a few things.

Angular 2 is a complete rewrite from version 1. This is because of the significant changes in web technologies over a couple of years. Angular 2 also leverages ECMAScript 2015(ES6) making it modern with the changes in the web industry as compared to Angular 1 which was built on ES5. However, you can still leverage on ES6 features for Angular 1 applications by using javaScript compilers like babel.

The introduction of web components, progressive web apps and mobile development has changed the way we build web applications. Angular 2 was designed to leverage these technologies making it the best framework to build robust, fast, efficient and cross-platform applications. I will not be explaining all the benefits here, therefore I would recommend you take a look at Angular 2 features and benefits documentation for more details.

Despite these differences, these two versions share the same philosophy and features. Some of these features include:

All these features are available in both versions. The only difference is the approach on which they are implemented. Therefore, learning either of these versions will not be considered a waste.

If you compare these versions based on speed, performance and relevance Angular 2 comes out on top. So yes I will tell you to go learn Angular 2. However, as a developer, you learn tools because they enable you to achieve certain goals or solve problems for your client. Most companies out there have systems running on Angular 1 and probably will be for a long time. This means Skills for Angular 1 will still be required to do maintenance and even upgrade to Angular 2 later.

In my opinion, I will advise you to learn both Angular 1 and 2 to get a competitive edge in the industry. Here are some answers from Quora on the same issue.


Prerequisites

This tutorial focuses on AngularJS concepts and therefore requires basic understanding of the following technologies;

  • HTML
  • CSS
  • JavaScript

AngularJS - MVC Architecture

Model View Controller(MVC) is a software design pattern for developing web applications. In this pattern, different features are broken into components to separate responsibilities. The model contains the data and logic, the view contains the visual layout and presentation, while the controller connects the two.

In AngularJS, the MVC pattern is implemented in JavaScript and HTML. The view is defined in HTML while the model and controller are implemented in JavaScript.

Model

The model is responsible for managing the data for the application. It responds to the requests from the view and the instructions from the controller to update itself. Models may contain functions that are invoked based on the user input or other activities that trigger changes to the model data.

In AngularJS services may be referred as the model. They define the data to be consumed by the view by fetching it from the server or manipulate it to fit what is required based on the user interactions with the view.

Below is an example of a service that fetches and returns data from an endpoint.


...
function MyService($http) {

// Fetch data from the server
  this.all = function() {
    return $http.get('/somedataurl/')
  }
}
...

The controller will leverege this service to get data from the server and bind it to the view.

View

This is the presentation layer for the Angular application where the visualisation of the model state happens. Changes from the model will be reflected in the view based on the controller's decision to present data.

Angular uses HTML templates to render data from the controller. Below is an example of an Angular template.

...
<h1>This is the view </h1>
  <div ng-view>
    <div id="message-title">Say something</div>
  <div id="message">{{ message }}</div>
</div>
  ...

Controller

The controller is responsible for responding to user inputs and perform interactions on the data model objects. It receives input, validates it and then performs the business operation that modifies the state of the model.

It pulls together the model used by the view and sets up any corresponding dependencies needed to render the view or handle input from the consumer of the view.

Let's look at an example below


function MyController(MyService) {

   // The controller business logic goes in here
   this.data = Myservice.all();

}

We have stated that controllers act as middlemen between the views and the models. In the above example we have injected the MyService model to the controller, then used its functionall to get the data from the server and passed it to a scoped variable data which can be accesed from the view.


What Makes AngularJS stand out?

In the above section, we talked about Angular and how it fits into the MVC pattern. We also looked at some examples in that regard. In this section, we are going to look at the features that make it stand out.

Code Organization

When it comes to front-end, the code structure has never been considered to be a priority. It has always been the code, browser and the refresh button until you get things working. If this is still your approach of building web applications then you are in for the surprise - not a good one at that.

This approach may work if you are building a prototype, but when it comes to building complex applications then structure becomes key. MVC pattern provides us with the blue-print on how to structure our code.

With Angular, you can build solid, well structured and fully testable applications in no time. This not only saves you time but also the maintenance nightmares that comes with unstructured code base.

// First module for some feature
angular.module('anotherModule', []);

// Another module for another feature
angular.module('someOtherModule', []);

// Adding them as dependecy of the main module
angular.module('mainModule', ['anotherModule','someOtherModule']);

Magic of Two-Way Data Binding

Data binding is the automatic synchronisation of data between the view (HTML) and the model. Binding data with plain javaScript can be a pain in the neck.

Let's look at the example below of how we could implement two-way data binding in plain javaScript.

To achieve data binding, we have used event listener onkeyup. This event triggers when the keyboard key is released and will in turn execute the callback function which will update the view.

This works fine, but imagine writing this code for a complex app: you guessed right, your codebase will be too combusome and hard to maintain. Now compare the example above with the one below.

Wow! clean, simple and elegant. With few lines of code we have achieved the same results.

Angular provides two-way data binding out of the box when binding components with specific models. Whenever the model changes - in our case the input field dataToBind, the view will be updated automatically . The same applies when the value of the components change, the bound model will also be changed.

What this means is that you can carry operations on the model and Angular guarantee that the changes will be reflected in the view. This saves you the stress of writing tonnes of boilerplate code and DOM manipulations just to get you started as shown in the first example.

Routing support

Nobody likes reloading browsers this day, I know I don't. With the advent of HTML5 and it's related API's, redirecting to new pages when a user clicks button or navigation is a thing of the past. Instead, we can asynchronously load content to the same page and just change the URL in the browser to reflect the change. This provides the user with desktop-like experience on the web.

With Angular we can very easily build Single Page Applications (SPA) with minimal effort. Angular was built to build web apps that provide desktop experience. You can basically create views from different URLs and Angular will load the appropriate view in the main page when a specific URL is requested.

This also enables us to logically divide our application into small pieces and integrate them through routing.

We have amazing articles on AngularJS routing on our website, In your own free time I will recommend you take a look at the following articles by Chris Sevilleja to get a deeper understanding of this concept.

Templating with HTML

AngularJS uses HTML as the templating language. The workflow becomes much simpler with plain HTML as the templating language, as the designers and developers don't have to depend on each other.

Designers can create UIs in the usual way and developers can use declarative binding syntax to tie different UI components with data models very easily.

<!-- Template for angular component -->
<div>
  <input type="text" ng-model="firstname">
  <input type="text" ng-model="lastname">

  <p> {{ firstname }}</p>
  <p> {{ laststname }}</p>
</div>

Out of the box Form Validation

Forms are the most important part of any CRUD (Create, Read, Update, Delete) application. Providing feedback to the user while the form is being filled provides a great user experience.

With that in mind, AngularJS forms incorporate real-time form validations, custom validators, matchers and much more. It also offers several CSS classes that indicate which state the form controls are in, either valid or invalid.

You can quickly write CSS rules against these classes to customise the look and feel of the form controls in different states as shown in the example above.

There is a lot more to Angular form validation than meets the eye. The example above is one of many ways you can apply form validation to Angular applications. We have a collection of articles that give a deeper look on how you can leverage this feature to build robust applications that provides seamless user experience.

Here are few honourable mentions I would recommend you take a look at and I promise they will be worth your time.

Supports Dependency Injection

AngularJS provides full support for dependency injection. This means that our code is not in charge of obtaining its own dependencies, rather they are injected automatically by a dependency injection container. For more details on dependency injection, read this Wikipedia page

...
// A service we need to do something in our controller
function MyService() {
  this.doSomething = function() {
    // Do something
  }
}

// Injecting MyService makes it accessible in our controller
function MyController( MyService) {
  // You can now use the service methods in here.
  Myservice.doSomething()
}
...

Let's look at an example.

In the example above we have defined a service called SecreMessage. It contains a method get which returns a secrect message. This service is then injected to the controller making the method get accessible inside the controller, we can invoke the method SecretMessage.get() inside the controller as shown above.

With this approach, each component of the app is loosely coupled to the others and we can test each one in isolation. This makes our app more testable and maintainable.

It's Testable

Testing your application during development helps you to fix bugs right away, which you would have otherwise encountered unexpectedly further down the line. Being a modern framework, AngularJS favours Test Driven Development and offers out of the box support for unit and End-to-End testing.

This enables you to build robust web applications. There is really no excuse not to test your application.

Adam Morgan has a very awesome article Testing AngularJS with Jasmine and Karma. I strongly recommend you take a look at it to get you started.


Anatomy of AngularJS Application

Before building an Angular application you should be aware of many different components of AngularJS. Here I will outline the important components that you should be aware of before we move any further. Some of these components will be covered in details in subsequent articles in this series.

Scope

This is the context that holds the data models and functions. Usually, the controller sets these models and functions into the scope, therefore it acts as the glue that binds the controller and the view.

  function MyController () {

    // Attach data to the view
    this.name = 'My awesome name';

    // Attach function to the view
    this.update = function() {
      // code to do something
    }
  }

Directives

This is a feature that introduces new syntax to HTML. It extends HTML with custom elements and attributes which add new functionality and provide a declaritve way on building web components.

AngularJS comes with a lot of in-built directives such as ng-app, ng-bind, ng-click, ng-repeat etc. Inbuilt Angular directives are prefixed with ng keyword. Angular does this to avoid conflict with any other user-defined directives.

  <!-- custome element that create a date picker-->
  <date-picker></date-picker>

In the example above, we have a custom elements that creates a date-picker using Angular directive construct.

Expressions

This is javaScript like code snippets that are mainly placed in interpolation bindings. They are useful in accessing scope models and functions in the view. They are represented by double curly braces {{ }} in the HTML.

Using the example we had in scope above, we can access the value of the name in HTML template as follows.

  <!-- This will bind the value of this.name to the view -->
  <p> {{ name }}</p>

Templates

This is the actual HTML that Angular uses to represent the state of the model. This is a combination of HTML and expression {{ }} which Angular will use to present the bound data. Above is a good example of an Angular template.

Bootstrapping an Angular Application

We have been talking about Angular features, what you need to know to get you started. Now lets look on how we can bootstrap an Angular application. Bootstrapping AngularJS application can be done either Manually or Automatically.

Manual Bootstrapping

If you need to have more control over the initialization process, you can use a manual bootstrapping method. The best scenario when you will need to do this include using script loaders or the need to perform certain operations before Angular compiles a page.

...
// Manualy bootstrap the app when the document has been loaded.
angular.element(document).ready(function() {
  angular.bootstrap(document, ['myApp']);
});
...

What happens here is that Angular will start to compile the page when the document has been fully loaded.

Automatic Bootstrapping

Another alternative will be to automatically bootstrap your application. This is done by using ng-app directive. Most of the applications you may come across are actually bootstrapped this way. In this scenario, you are letting Angular do all the work for you.

...
<!-- Bootstraping the angular app using ng-app directive -->
<div ng-app="MyApp">
  <h4>Will return the sum of 5 + 8 if the app is bootstrapped properly</h4>
  <h5> {{ 5 + 8}} </h5>
</div>

<script type="text/javascript">
  // Declaring the main app module
  angular.module('MyApp', []);
</script>

Lets see it in action in the example below.

When this page is served to the browser, the Angular application will look to the root element and compiles the application. The ng-app app directive is used to define the root element. The ng-controller directive is used to tell Angular which controller to use to bind the template.

Conclusion

AngularJS is a javaScript framework that enables you to build structured web applications in a declarative manner. It's a compatible with the MVC development pattern thus enabling us to implement abstraction and separation of concerns in our front end code.

In this article we have looked at the basics that we need to venture deeper into Angular . In the next article in this series, we will be looking into modules, controllers and data binding in depth.

Mean time I recommend you look into Angular style guides on how to write clean and elegant AngularJS code. Also make an effort to read AngularJS Best Practices: Directory Structure by Ado Kukic to get you up to speed on how to structure your application for scalability and maintenance reasons.

Nyambati Thomas

I am a full stack developer with extensive experience working with web technologies. I am competent in MEAN stack, databases such as PostgreSQL, Firebase, MongoDB, and MySQl. I am currently exploring Golang and python.

Software Developer @Andela