Saturday, 17 June 2017

Explore the new features in Angular 2


Angular 2 is here, and it is a brave new world! With language improvements, tooling enhancements, new browser features and the best practices gleaned from AngularJS 1.X, it has evolved from a framework that provides us with a mostly sane approach to building web apps to a full-featured platform we can use to target everything. Angular 2 is completely evolved, and that means everyone is going to have at least one — if not many — moments of disorientation when they are learning the framework.

In this article, we are going to take a tour around a simple Angular 2 website and get acquainted with Angular components and how they work. Under the hood of most Angular 2 mechanisms is a vanilla ES6 class, with Angular using metadata to enhance the class with all its powers. We will use component metadata to tell Angular how the class is supposed to behave.
This article will focus on just the essentials. Check out the repository at and the accompanying screencast for a treasure trove of extra tips and techniques.

The root component

The single most important theme in Angular 2 is components. These are the basic building blocks that everything else is built upon. As a result, the genesis of every Angular 2 application is its ‘root’ component. In the body of our main HTML file we start with a single app element that is the entry point for our application. Everything inside this tag is visible until Angular is bootstrapped.
// index.html
<body>
<app>Loading…</app>
</body>
To bootstrap the app, we import the bootstrap method from the platform-browser-dynamic package. We also import the root component. Then we call the bootstrap method, passing in the root component and an array of providers.
// boot.ts
import {bootstrap} from ‘@angular/platform-browserdynamic’;
import {AppComponent} from ‘./app.component’;
bootstrap(AppComponent, []);
To create a component, create a TypeScript class called AppComponent to represent the component, and then import the Component class from the Angular core. Finally, decorate the class by adding @Component metadata and passing a configuration object to it.
You can enhance your component by augmenting the config object with properties such as selector (the HTML tag representing the component), template and styles. You can also specify an array of providers (services, for example) and directives. In a moment we are going to repeat this same process when we create a child component.
Note that in Angular 2, it is considered best practice to favour fine-grained components with a single, specific task. A rule of thumb is that you have accomplished this when your HTML is small enough to be inlined within the decorator without being cumbersome.
// app.component.ts
import {Component} from ‘@angular/core’;
@Component({
selector: ‘app’,
styles: [ h1 { text-align: center; } ],
template: <h1>Hello Angular 2!</h1>
})
export class AppComponent {}
You’ll find a working example in the ‘01-gettingstarted’ branch of the GitHub repository.

Child components

Let’s create a home component. The first thing we are going to do is create our HomeComponent class and set the title and body properties. We will also import Component from @angular/core so we can use it to decorate our new class in just a moment.
// home.component.ts
import {Component} from ‘@angular/core’;
export class HomeComponent {
title: string = ‘Home Page’;
body: string = ‘This is the about home body’;
}
We are going to enhance our Component metadata with the selector we want to use to target our component, the path to the HTML template and some CSS for aesthetic purposes.
// home.component.ts
import {Component} from ‘@angular/core’;
@Component({
selector: ‘home’,
template: require(‘./home.component.html’),
styles: [
.content-card > .mdl-card__title {
color: #fff;
height: 176px;
background: url(‘../images/home-card.jpg’) center / cover;
}
]
})
export class HomeComponent {
title: string = ‘Home Page’;
body: string = ‘This is the about home body’;
}
We can bind to any public properties or methods in our TypeScript class, so in our home.component.html file we are going to use curly brace string interpolation to render our title and body values.
// home.component.html
<div class=”content-card”>
<div class=”mdl-card__title”>
<h1>{{ title }}</h1>
</div>
<div>
{{ body }}
</div>
</div>
We can repeat this process for an ItemsComponent and AboutComponent and then make all three of our newly minted child components available to the AppComponent by importing them and injecting them in via the directives array on the class metadata.
// app.component.ts
import {Component} from ‘@angular/core’;
import {AboutComponent} from ‘./about/about.component’;
import {ItemsComponent} from ‘./items/items.component.ts’;
import {HomeComponent} from ‘./home/home.component’;
@Component({
selector: 'app',
template: require('./app.component.html'),
styles: [require('./app.component.css')],
directives: [HomeComponent, AboutComponent,
ItemsComponent]
})
export class AppComponent {}
Angular 2 components by nature are self-contained, so when we want to render them on the page, we just need to add our component selectors to the markup as you can see below. The pleasant side effect of this component-driven architecture is that our HTML is now a DSL and very descriptive of the domain model we are working in.
// app.component.html
<main>
<div>
<home></home>
<about></about>
<items></items>
</div>
</main>
If you check out the ‘02-components’ branch of the repository, you will see a working example of this.

Routing

Creating a bunch of components and dumping them on a page is interesting but not necessarily reflective of how we build apps in real life. We need to be able to navigate between components as if they were pages in a website, and we can use the ComponentRouter to accomplish this task.
We are going to update our boot.ts file slightly by importing the ROUTER_PROVIDERS from the Angular router package. We will then insert ROUTER_PROVIDERS into our providers array in the bootstrap method call.
// boot.ts
import {bootstrap} from ‘@angular/platform-browserdynamic’;
import {ROUTER_PROVIDERS} from ‘@angular/router’;
import {AppComponent} from ‘./app.component’;
bootstrap(AppComponent, [
ROUTER_PROVIDERS
]);
Because this is a small application, we are going to configure our routes in the root component. We will start by importing the Routes decorator and the ROUTER_DIRECTIVES from Angular’s router package. We need the ROUTER_DIRECTIVES if we want to create links to our routes in our HTML.
//app.component.ts
import {Component} from ‘@angular/core’;
import {Routes, ROUTER_DIRECTIVES} from ‘@angular/
router’;
import {AboutComponent} from ‘./about/about.component’;
import {ItemsComponent} from ‘./items/items.component.ts’;
import {HomeComponent} from ‘./home/home.component’;
@Component({
selector: ‘app’,
template: require(‘./app.component.html’),
styles: [require(‘./app.component.css’)],
directives: [ROUTER_DIRECTIVES]
})
@Routes([
{path: ‘/’, component: HomeComponent},
{path: ‘/home’, component: HomeComponent},
{path: ‘/about’, component: AboutComponent},
{path: ‘/items’, component: ItemsComponent},
{path: ‘/*’, component: HomeComponent}
])
export class AppComponent {}
We will then decorate our AppComponent with some additional @Routes metadata that contains the routing table for our application. A basic route is an object that consists of a path and the component that the path links to.
Did you notice the ‘/’ and ‘/*’ routes? The former matches the root URL of the application (http://example.com) and serves the HomeComponent, while the latter matches any unregistered URLs and serves HomeComponent.
Now that our routes are configured, we can update our templates to link to specific routes. To link to a registered route in the component HTML, we will place a [routerLink] attribute on an anchor tag.
The value should be an array of paths. In this case, since we don’t have any extra parameters, we just need one path (which we specified in the @Routes decoration).
// app.component.html
<header>
<div>
<nav>
<a [routerLink]=”[‘/home’]”>HOME</a>
<a [routerLink]=”[‘/about’]”>ABOUT</a>
<a [routerLink]=”[‘/items’]”>ITEMS</a>
</nav>
</div>
</header>
<main>
<div>
<router-outlet></router-outlet>
</div>
</main>
If you check out the ‘03-routes’ branch of the repository, you’ll see our routing table in action.

In closing

All complex systems are just composed of a bunch of smaller systems that work together to produce something impressive. Angular 2 is incredibly powerful, and because of that it can seem like we are standing at the foot of a cliff trying to figure out how we are going to get to the top.
The process becomes far less daunting when we realise we are just working with components that can be stamped out using the simple process of creating the class, importing our dependencies, decorating our class, enhancing our component and repeating from the beginning.

Angular 2 Tutorial - The Architecture of an Angular 2 Application


Angular 2 is beta now, what this means is though it is not production ready, the angular team is confident that you can build apps with Angular 2. This also means that when Angular 2 is ready for production there won’t be major changes in the implementation compared to what it is now.
Though one might argue it is still too early, we are suggesting to you that this is the right time to get acquainted with it and get your hands dirty. This will give you a head-start when Angular 2 is ready and when you are ready to develop production apps with Angular 2.
Whenever we get started with a new framework it is of pivotal importance to know how the framework works. So we first need to understand the architecture of Angular 2 and get familiar with some of the key concepts of Angular 2 followed by which we will set up our development environment.

Architectural Overview

Angular is designed to be modular, an Angular 2 app comprises of several components, which are connected via routing or selectors, these components may have templates attached to it which may display component properties and attach events to interact with the properties. A component may use a service, to access a particular feature or perform a very specific task. Services must be injected into components before they can be used from within the component, this is referred to as Dependency Injection, which has also been a key feature of Angular 1.x.
enter image description here
The above diagram shows an overall overview of the basic architecture of a skeleton Angular 2 app. Lets
look into few of the important concepts in detail.

Modules

Angular App comprises of several Modules, a module typically exports something of a purpose. A module is a set of similar utilities that perform a similar task. Typically a module may export a class which we may be imported in other modules. Angular 2 itself ships in large modules, some of them are ‘angular/core‘, ‘angular/router‘ and there are more.

Components

Components are the basic building blocks of an Angular 2 app. A component is typically a type-script class which has a template attached, it usually assembles a screen, ui-element or a route in the application. A component may have child components. Components can be navigated using routing or selectors.
A component has a metadata/ decorator associated which describes the component. Metadata tells angular that the associated TypeScript class is actually to be considered as a component.

Services

A good Angular 2 application is one in which specific tasks are assigned to different services. A component may consume these services to perform these tasks. Typically a component should only deal with the user experience and the display of properties and use services to perform heavy behind the scenes operations. A service must be injected in to the controller before it can be used. This is done via dependency injection.

Dependency Injection

One of the key features of AngularJS is the dependency injection. Components need to use services to perform tasks, and these services are injected into the component via the injector. The injector provides the instance of the service, so that it can be used in the component. The idea behind dependency injection is to separate out concerns into smaller units and make components depend on these units to perform specific tasks, making your application more manageable and easy to unit test.

Directives

Directives are everywhere in Angular 2. A directive is a TypeScript Class with a metadata. Directives may or may not have a template attached. Component is an example of a directive with a template. There are two kinds of directives in Angular 2, structural and attribute directives. Structural directives modify the structure or layout of the DOM. Attribute directives alter the behavior of the elements. Some of the examples of pre-built directives are ngForngIfngSwitchngModel etc.

TypeScript

Angular 2 application can be written in JavaScriptDart or TypeScript. For this tutorial we will be looking at a setup with TypeScript.
TypeScript is Microsoft’s extension of JavaScript. TypeScript is a super-set of ES6 which in turn is a super set of the standard JavaScript (ES5). This means whatever that can be done with ES5 or ES6 can be written in TypeScript. In-fact you can most of the times write in plain old JavaScript in a TypeScript program. TypeScripts adds important features like annotationsinterfaces and types in addition to classes and modules offered by ES6 on top of ES5. Browsers do not understand TypeScript
and hence it has to be transpired into ES5 and this can be done using the TypeScript compiler.

Development Setup

This section will deal with the setup required to write Angular 2 apps in TypeScript. In the process to do so, we will be building a simplest form of Angular 2 app and also have a look at a skeleton folder structure for Angular 2 apps.
In short this section will setup our base to eventually build better and larger apps with Angular 2.
Note: This article is written for Angular 2.0 beta. The Angular 2 repo is subjected to change, if you find any discrepancies please write to us about it and if possible suggest the fixes

Install Node

npm will be used as our package manager and our app will run on node. If you have node installed awesome; if not, then head over to the official node website and download the appropriate version.

Setup a Skeleton App

Now lets get a skeleton app structure from an app that I have already created. I will explain the contents later, for now follow along.
Clone the repository.
Alternatively you can download and extract the code form here.

App structure

Once you have completed the above step successfully, you should be able to see the following project structure.
enter image description here
APP
Angular apps are built out of several linked or nested components, our app folder here contains a components directory, which will hold the apps different components.
ASSETS
Assets is a directory which will contain non angular data required by our app, for example style-sheets.
PACKAGE.JSON
Package.json holds information that allows npm to identify the project dependencies and help install them with a single command.
Below is our package.json file, which is similar to the one provide by the Angular 2 team for the quick-start application. It contains a starter-set of dependencies required by Angular 2 project identified by the Angular 2 team.
package.json
{
  "name": "angular2-setup",
  "version": "1.0.0",
  "scripts": {
    "start": "concurrent \"npm run tsc:w\" \"npm run lite\" ",<br />
    "tsc": "tsc",
    "tsc:w": "tsc -w",
    "lite": "lite-server",
    "typings": "typings",
    "postinstall": "typings install"
  },
  "license": "ISC",
  "dependencies": {
    "angular2": "2.0.0-beta.7",
    "systemjs": "0.19.22",
    "es6-promise": "^3.0.2",
    "es6-shim": "^0.33.3",
    "reflect-metadata": "0.1.2",
    "rxjs": "5.0.0-beta.2",
    "zone.js": "0.5.15"
  },
  "devDependencies": {
    "concurrently": "^2.0.0",
    "lite-server": "^2.1.0",
    "typescript": "^1.7.5",
    "typings":"^0.6.8"
  }
}
While running the application I encountered a type-error in the chrome browser, to fix this I upgraded the es6-shim version from 0.33.3 (which is recommended by Angular 2 team) to 0.34.4. Details can be found here.
The scripts defined in the file run few commands for example npm start will run the typescript compiler (tsc) and then run lite-server. Commands defined in post install run after npm has finished installing other dependencies.

tsconfig.json

tsconfig.json
{
  "compilerOptions": {
    "target": "es5",
    "module": "system",
    "moduleResolution": "node",
    "sourceMap": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "removeComments": false,
    "noImplicitAny": false
  },
  "exclude": [
    "node_modules",
    "typings/main",
    "typings/main.d.ts"
  ]
}
tsconfig.json is the configuration file for TypeScript projects. It holds configurations such as compiler options, files to be included excluded, etc. The compilerOptions instructs TypeScript compiler, how to compile typescript files.
The exclude block instructs typescript compiler to exclude folders and files.
TYPINGS.JSON
typings.json
{
  "ambientDependencies": {
    "es6-shim": "github:DefinitelyTyped/DefinitelyTyped/es6-shim/es6-shim.d.ts#6697d6f7dadbf5773cb40ecda35a76027e0783b2"
  }
}
Some libraries/ framework extend JavaScript environment with features that type script compiler does not support. To make the typescript compiler understand these enhancements we add respective d.ts files in typings.json

First Component

/app/components/welcome/welcome.component.ts
import {Component} from 'angular2/core';
@Component({
    selector: 'my-app',
    templateUrl: '../app/components/welcome/welcome.template.html'
})
export class WelcomeComponent {
    constructor() {
        var self = this;
        self.displayName = '';
    }
    setDisplayName(value){
        var self = this;
        self.displayName = value;
    }
}
This is the complete welcome.ts file. Parts of code are explained below.
import {Component} (welcome.component.ts)
import {Component} from 'angular2/core';
To create a component we will need the component class which is shipped with ‘angular2/core’ module. importstatement tells TypeScript to import some exported entity from a module.
Decorator (welcome.component.ts)
@Component({
    selector: 'my-app',
    templateUrl: '../app/components/welcome/welcome.template.html'
})
The @component decorator/metadata describes a component and also tells Angular the the following class has to be treated as an Angular Component. The selector property describes the element name for our Component. So where ever we will use the element <my-app></my-app>, Angular will render our component.
Class (welcome.component.ts)
export class WelcomeComponent {
    constructor() {
        var self = this;
        self.displayName = '';
    }
    setDisplayName(value){
        var self = this;
        self.displayName = value;
    }
}
A class contains logic that would display, modify properties to be displayed to the user in the UI. We are exporting the class, so that we can import it some where else.
Our WelcomeComponent contains a constructor() function and a setDisplayName() method. A constructor is defined with the constructor key word in TypeScript or in ES6.
In Angular 1 we would do using a controller what a component class does in Angular 2.
/app/components/welcome/welcome.template.html
<h1 class="displayHead" *ngIf="!!displayName">Welcome to the world of Angular 2</h1>

<h2 class="userName" [hidden]="!displayName">{{displayName}}</h2>

<div *ngIf="!displayName">
    <label>Enter Your Name</label>
    <input [(ngModel)]="name"/>
    <button (click)="setDisplayName(name)">Enter</button>
</div
We won’t be going into details on events and property bindings in this tutorial, but here is some explanation to above template.
  • [hidden]: Property binding
  • (click): Event Binding. We are invoking setDisplayName method on click event.
  • [(ngModel)]: This is how you do, two-way data-binding in Angular 2

index.html

index.html
<html>
  <head>
    <title>Angular 2 QuickSetup</title>
    <meta name="viewport" content="width=device-width, initial-scale=1"><br />
    <link rel="stylesheet" type="text/css" href="assets/styles/style.css">
    <!-- 1. Load libraries -->
    <!-- IE required polyfills, in this exact order -->
    <script src="node_modules/es6-shim/es6-shim.min.js"></script>
    <script src="node_modules/systemjs/dist/system-polyfills.js"></script>
    <script src="node_modules/angular2/bundles/angular2-polyfills.js"></script>
    <script src="node_modules/systemjs/dist/system.src.js"></script>
    <script src="node_modules/rxjs/bundles/Rx.js"></script>
    <script src="node_modules/angular2/bundles/angular2.dev.js"></script>
    <!-- 2. Configure SystemJS -->
    <script>
      System.config({
        packages: {
          app: {
            format: 'register',
            defaultExtension: 'js'
          }
        }
      });
      System.import('app/main')
            .then(null, console.error.bind(console));
    </script>
  </head>
  <!-- 3. Display the application -->
  <body>
    <my-app>Loading...</my-app>
  </body>
</html>
In index.html we are loading our required libraries and configuring systemJS.
Systemjs is our module loader. By defining packages in System.config we are setting systemjs setting for files loaded from ‘app/’ folder. We are setting the defaultExtension to js since we will be loading files transpiled into .jsfrom .tsSystems.import('app/main') loads the main.ts file where we are bootstraping the application, we will have a look at main.ts below. Systemjs configurations may deffer depending on the project folder structure. You can lean more about Systemjs configurations here.
Finally we are loading our welcome component by placing the my-app selector. If you remember we named our component element as my-app

Bootstrapping app with main.ts

main.ts
import {bootstrap} from 'angular2/platform/browser'
import {WelcomeComponent} from './components/welcome/welcome.component'
bootstrap(WelcomeComponent);
Here we tell angular to load our WelcomeComponent i.e the root component.

Run the app

Before running the app we need to do one more thing that is left out. Install all the required npm packages. Fire up your terminal and navigate to the working directory and run the following command.
 npm install
This may take a while, during the installation you may see some warnings but that is fine.
Next, to run our first Angular 2 app execute the below command.
npm start
This would fire up the lite server and run our app in the browser.
enter image description here
So here we have our first app with Angular 2. Download and play around with the code and explore new stuffs, you will learn more when you will try it yourself.

Conclusion

This tutorial intended to acquaint you with Angular 2 and set us up on mark to build larger apps with it. We have barely scratched the surface and there is more to learn. Stay tuned we will go into further details and build real apps with Angular 2 in coming tutorials.

Thursday, 8 June 2017

Tips and Best Practices for the AngularJS Framework

AngularJS is one of the most popular JavaScript libraries for front-end development. It’s developed and supported by Google, and it allows developers to create fast, efficient client-side web applications. Some long-time JavaScript developers find some AngularJS functionality and syntax new and a bit challenging, especially those new to the Model-View-Controller (MVC) structure, which can be difficult to learn. If you’re diving into AngularJS for the first time or just looking for a better way to manage your Angular projects, here are some tips you might want to keep in mind along the way.

1. REWORK THE DEFAULT DIRECTORY STRUCTURE

It’s helpful to know that you can restructure Angular’s default directories. The default directories you’re given will depend on the type of software you’re writing. For example, you’re given directories for controllers, views, services, templates and models. This structure works fine for smaller projects where you can easily locate files for a specific module. If you’re working with 10 files for an app, you can use this default structure with little hassle.
However, once the application grows to a medium or large size, you could be working with hundreds of files. Trying to find a file for a specific module can be very tedious, making it more effective to rework your directory structure to group your project by logical sections. For instance, the following directory structure could work:
app/
app.js
dashboard/
frontpage.html
frontpagecontroller.js
frontpageservice.js
order/
order.html
ordercontroller.js
orderservice.js
In this example, two logical components (front page and order) are given their own directories. If one of these modules breaks, you know immediately where to find it.

2. KEEP PRESENTATION LOGIC OUT OF CONTROLLERS

It’s easy for a programmer to fall into the habit of presentation manipulation of the DOM in a controller, which can be problematic in an MVC architecture.
In an MVC architecture, every module is separated into either the model, view or controller. The view is where your presentation logic is coded. The presentation is anything to do with the DOM. If you need to change a value in any HTML element, you should only use the presentation layer to do it.
When you perform presentation execution in the controller rather than the view, you break the separation of layers. When you or another developer goes back to maintain the code, you can miss the code in your controller that shouldn’t be there. This can lead to bugs.
Bear in mind that MVC architecture is much different than old-school, linear web languages. Once you get used to it, however, you’ll find it much more manageable when you need to deal with large-scale applications.

3. USE THE TRACK BY FEATURE ON REPEATED LISTS

It’s common to write lists from objects in AngularJS. Whenever you need to work with the DOM, though, your code becomes a little less efficient. Of course, you can’t avoid working with the DOM altogether, but you can minimize the amount of times it’s interfaced.
One way to limit the number of times a list must be re-rendered is to use the “track by” item.
As an example, let’s take a look at this list:
<div ng-repeat="listitem in orderList">

</div>
In the above code, every time the DOM is rendered, the list is rewritten to the page. This means your code manipulates the DOM every time it runs. There is a more efficient way to handle this type of procedure. Take a look at the following code:
<div ng-repeat=" listitem in orderList track by item.orderid">
</div>
Notice the second set of code uses the “track by” statement. It does the same process—it still lists all orders in a list section—but the second block of code speeds up the process and makes your application much more efficient by allowing you to specify your own key instead of generating random unique IDs.

4. USE DEPENDENCY INJECTION

Dependency injection is a very broad topic, but we’ll explain it briefly here. Dependency injection is a way to decouple parts of your application from the main logic. The idea is that you can make major changes to the business logic or models of the main application. The dependency is seen as a service, and you pass this dependency to the client.
If you’ve worked in other MVC applications, you’ve probably worked with dependency injection. If you haven’t, here’s how it looks in AngularJS.
angular.module(‘YourAppName’).controller('YourControllerName', ['$scope', 'YourServiceName',function($scope, YourServiceName) {
// controller code goes here
}
]);
With this, you can change the controller code without directly affecting the service. Dependency injection is a more advanced topic, but it’s essential for enterprise-level applications where code changes often and you have several developers working on the same solution.

5. USE ANGULARJS-SPECIFIC TESTING TOOLS

There are options when it comes to testing, but be sure to choose carefully. Chrome comes with its own developer tools, and many developers use Firefox plugins to test JavaScript code. But AngularJS is a highly modified form of JavaScript. Because Google developed AngularJS, the most common (and probably the safest) tool to use is the Chrome extension ng-inspector.
This tool can help you debug, review, test, and determine if you have any errors in your code. It keeps track of the scope, and you can view the element attached to the scope.

AngularJS is a new, powerful, client-side technology that provides a way of accomplishing really powerful things in a way that embraces and extends HTML, CSS and JavaScript, while shoring up some of its glaring deficiencies. It is what HTML would have been, had it been built for dynamic content.
In this article, we will cover a few of the most important AngularJS concepts to get the "big picture." It is my goal that, after seeing some of these features, you will be excited enough to go and build something fun with AngularJS.
Think of your model as the single-source-of-truth for your application. Your model is where you go to to read or update anything in your application.
Data-binding is probably the coolest and most useful feature in AngularJS. It will save you from writing a considerable amount of boilerplate code. A typical web application may contain up to 80% of its code base, dedicated to traversing, manipulating, and listening to the DOM. Data-binding makes this code disappear, so you can focus on your application.
Think of your model as the single-source-of-truth for your application. Your model is where you go to to read or update anything in your application. The data-binding directives provide a projection of your model to the application view. This projection is seamless, and occurs without any effort from you.
Traditionally, when the model changes, the developer is responsible for manually manipulating the DOM elements and attributes to reflect these changes. This is a two-way street. In one direction, the model changes drive change in DOM elements. In the other, DOM element changes necessitate changes in the model. This is further complicated by user interaction, since the developer is then responsible for interpreting the interactions, merging them into a model, and updating the view. This is a very manual and cumbersome process, which becomes difficult to control, as an application grows in size and complexity.
There must be a better way! AngularJS' two-way data-binding handles the synchronization between the DOM and the model, and vice versa.
Here is a simple example, which demonstrates how to bind an input value to an <h1> element.
This is extremely simple to set up, and almost magical…
It's important to realize that at no point does AngularJS manipulate the template as strings. It's all the browser DOM.
In AngularJS, a template is just plain-old-HTML. The HTML vocabulary is extended, to contain instructions on how the model should be projected into the view.
The HTML templates are parsed by the browser into the DOM. The DOM then becomes the input to the AngularJS compiler. AngularJS traverses the DOM template for rendering instructions, which are called directives. Collectively, the directives are responsible for setting up the data-binding for your application view.
It is important to realize that at no point does AngularJS manipulate the template as strings. The input to AngularJS is browser DOM and not an HTML string. The data-bindings are DOM transformations, not string concatenations or innerHTML changes. Using the DOM as the input, rather than strings, is the biggest differentiation AngularJS has from its sibling frameworks. Using the DOM is what allows you to extend the directive vocabulary and build your own directives, or even abstract them into reusable components!
One of the greatest advantages to this approach is that it creates a tight workflow between designers and developers. Designers can mark up their HTML as they normally would, and then developers take the baton and hook in functionality, via bindings with very little effort.
Here is an example where I am using the ng-repeat directive to loop over the images array and populate what is essentially an img template.
It is also worth mentioning, as a side note, that AngularJS does not force you to learn a new syntax or extract your templates from your application.
AngularJS incorporates the basic principles behind the original MVC software design pattern into how it builds client-side web applications.
The MVC or Model-View-Controller pattern means a lot of different things to different people. AngularJS does not implement MVC in the traditional sense, but rather something closer to MVVM (Model-View-ViewModel).
The model is simply the data in the application. The model is just plain old JavaScript objects. There is no need to inherit from framework classes, wrap it in proxy objects, or use special getter/setter methods to access it. The fact that we are dealing with vanilla JavaScript is a really nice feature, which cuts down on the application boilerplate.
viewmodel is an object that provides specific data and methods to maintain specific views.
The viewmodel is the $scope object that lives within the AngularJS application. $scope is just a simple JavaScript object with a small API designed to detect and broadcast changes to its state.
The controller is responsible for setting initial state and augmenting $scope with methods to control behavior. It is worth noting that the controller does not store state and does not interact with remote services.
The view is the HTML that exists after AngularJS has parsed and compiled the HTML to include rendered markup and bindings.
This division creates a solid foundation to architect your application. The $scope has a reference to the data, the controller defines behavior, and the view handles the layout and handing off interaction to the controller to respond accordingly.
AngularJS has a built-in dependency injection subsystem that helps the developer by making the application easier to develop, understand, and test.
Dependency Injection (DI) allows you to ask for your dependencies, rather than having to go look for them or make them yourself. Think of it as a way of saying "Hey I need X', and the DI is responsible for creating and providing it for you.
To gain access to core AngularJS services, it is simply a matter of adding that service as a parameter; AngularJS will detect that you need that service and provide an instance for you.
You are also able to define your own custom services and make those available for injection as well.
Directives are my personal favorite feature of AngularJS. Have you ever wished that your browser would do new tricks for you? Well, now it can! This is one of my favorite parts of AngularJS. It is also probably the most challenging aspect of AngularJS.
Directives can be used to create custom HTML tags that serve as new, custom widgets. They can also be used to "decorate" elements with behavior and manipulate DOM attributes in interesting ways.
Here is a simple example of a directive that listens for an event and updates its $scope, accordingly.
Then, you can use this custom directive, like so.
Creating your application as a composition of discrete components makes it incredibly easy to add, update or delete functionality as needed.
The AngularJS team feels very strongly that any code written in JavaScript needs to come with a strong set of tests. They have designed AngularJS with testability in mind, so that it makes testing your AngularJS applications as easy as possible. So there's no excuse for not doing it.
Given the fact that JavaScript is dynamic and interpreted, rather than compiled, it is extremely important for developers to adopt a disciplined mindset for writing tests.
AngularJS is written entirely from the ground up to be testable. It even comes with an end-to-end and unit test runner setup. If you would like to see this in action, go check out the angular-seed project at https://github.com/angular/angular-seed.
Once you have the seed project, it's a cinch to run the tests against it. Here is what the output looks like:
AngularJS Essentials
The API documentation is full of end-to-end tests that do an incredible job of illustrating how a certain part of the framework should work. After a while, I found myself going straight to the tests to see how something worked, and then maybe reading the rest of the documentation to figure something out.
We have covered six of the many AngularJS features that I love. I believe that these six features are essential for not only getting up and running with AngularJS, but also putting your application together in a way that is maintainable and extensible.
The website for AngularJS, http://angularjs.org, has plenty of working examples and plenty of excellent documentation. I also recommend checking out the amazing community on the AngularJS mailing list.
Let me know what you think!

Angular Tutorial (Update to Angular 7)

As Angular 7 has just been released a few days ago. This tutorial is updated to show you how to create an Angular 7 project and the new fe...