Tutorial

AngularJS 1.x Fundamentals (Part 1)

Draft updated on Invalid Date
Default avatar

By Nyambati Thomas

AngularJS 1.x Fundamentals (Part 1)

This tutorial is out of date and no longer maintained.

Introduction

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

Screenshot of the AngularJS website.

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, you will explore AngularJS fundamentals.

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 have 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.

Here are some answers from Quora on the same issue:

Prerequisites

This tutorial focuses on AngularJS concepts and therefore requires a 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 to 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 leverage 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 visualization 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 function all to get the data from the server and passed it to a scoped variable data which can be accessed 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 the front-end, the code structure has never been considered to be a priority. It has always been the code, browser, and refresh until you get things working. If this is still your approach to 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 blueprint 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 come with an 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 synchronization 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.

<div class="container">
  <h3>Data binding example</h3>
  <textarea id="dataToBind" class="form-control"></textarea>
  <p id="showBoundData"></p>
</div>

<script type="text/javascript">
// Get the elements we want to bind
var inputElement = document.getElementById('dataToBind');
var showElement = document.getElementById('showBoundData');

// Add an event listener to listen for keyup event
inputElement.addEventListener('keyup', function() {
  showElement.innerHTML = inputElement.value.toString();
});
</script>

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 cumbersome and hard to maintain. Now compare the example above with the one below.

<div class="container">
  <h3> Data binding example with Event Listeners </h3>
  <textarea ng-model="dataToBind" class="form-control"></textarea>
  <p> {{ dataToBind }} </p>
</div>

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

angular.element(document).ready(function() {
	angular.bootstrap(document, ['app']);
});
</script>

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 guarantees 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

With the advent of HTML5 and its related APIs, redirecting to new pages when a user clicks a 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 a 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 a desktop experience. You can basically create views from different URLs and Angular will load the appropriate view on 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.

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.

<div>
  <form novalidate class="css-form" name="myForm">
    Name: <input type="text" ng-model="user.name" class="form-control" required /><br />
    E-mail: <input type="email" ng-model="user.email" class="form-control" required /><br />
		<button type="submit" class="btn btn-success" ng-disabled="myForm.$invalid">save</button>
  </form>
</div>

You can quickly write CSS rules against these classes to customize 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 at how you can leverage this feature to build robust applications that provide a seamless user experience.

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.

// declare the main module
angular.module('app', [])
  // Define Secret Message service
  .service('SecretMessage', function() {
    this.get = function() {
      return 'This is a super secret message';
    }
  })
  // Injecting $scope and SecretMessage as dependecies of this controler
  .controller('DependencyController', function($scope, SecretMessage) {
    $scope.secretMessage = SecretMessage.get();
  })

// bootstraping the app
angular.element(document).ready(function() {
  angular.bootstrap(document, ['app']);
})

In the example above we have defined a service called SecreMessage. It contains a method get which returns a secret message. This service is then injected into 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 favors 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.

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 detail 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 a new syntax to HTML. It extends HTML with custom elements and attributes which add new functionality and provide a declarative way of 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.

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

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

Expressions

These are 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 the 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, let’s look at 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 includes 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.

<div class="box">
  <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 angular main module
angular.module('MyApp', []);


// Manually bootstrapping angular app
angular.element(document).ready(function() {
  angular.bootstrap(document, ['MyApp'])
})
</script>

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>

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 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.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about us


About the authors
Default avatar
Nyambati Thomas

author

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
Leave a comment


This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

Try DigitalOcean for free

Click below to sign up and get $200 of credit to try our products over 60 days!

Sign up

Join the Tech Talk
Success! Thank you! Please check your email for further details.

Please complete your information!

Get our biweekly newsletter

Sign up for Infrastructure as a Newsletter.

Hollie's Hub for Good

Working on improving health and education, reducing inequality, and spurring economic growth? We'd like to help.

Become a contributor

Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

Welcome to the developer cloud

DigitalOcean makes it simple to launch in the cloud and scale up as you grow — whether you're running one virtual machine or ten thousand.

Learn more
DigitalOcean Cloud Control Panel