AngularJS Introduction
AngularJS is a JavaScript framework that adds new features to HTML through special attributes.
What is AngularJS?
- AngularJS is a JavaScript framework written in JavaScript
- It is added to a page with a single
<script>tag - It extends HTML with directives, attributes that start with
ng- - It connects data and the page with two-way data binding
AngularJS support ended in January 2022. It receives no security fixes. Use this tutorial to maintain existing apps; for new work use modern Angular.
AngularJS vs Angular
| AngularJS | Angular | |
|---|---|---|
| Versions | 1.0 to 1.8 | 2 and later |
| Language | JavaScript | TypeScript |
| Main idea | Controllers and $scope | Components and signals |
| Support | Ended in 2022 | Active |
They are separate frameworks. You cannot simply "upgrade" AngularJS code to Angular; a migration means rewriting parts of the app.
Adding AngularJS to a Page
AngularJS is a single JavaScript file. The last version is 1.8.3, and many old projects use 1.8.2 or older. Older projects often load it from a CDN:
Example
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>In projects you maintain, you may also find it in a local folder such as lib/angular.min.js or installed with npm or Bower.
A Complete Example
Example
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
</head>
<body>
<div ng-app="" ng-init="shop='Gulshan Stationers'">
<h2>{{ shop }}</h2>
<p>Item: <input type="text" ng-model="item"></p>
<p>Quantity: <input type="number" ng-model="qty"></p>
<p>You ordered {{ qty }} x {{ item }}</p>
</div>
</body>
</html>Gulshan Stationers (typing "Notebook" and 3) You ordered 3 x Notebook
The example explained
| Part | What it does |
|---|---|
ng-app | Marks the area of the page that AngularJS controls |
ng-init | Sets a starting value (used here only for a demo) |
ng-model | Connects an input to a variable |
{{ qty }} | An expression that shows a value on the page |
When you type in an input, the variable changes, and every {{ }} that uses it updates immediately. This is two-way binding.
How AngularJS Starts
When the page loads, AngularJS:
- Looks for the
ng-appdirective - Treats that element and everything inside it as the app
- Reads all directives and expressions, and connects them to data
- Watches the data and updates the page when it changes
Anything outside the ng-app element is plain HTML.
Common Problems in Old Projects
- Slow pages with very large lists, because AngularJS checks every binding on each change
- Security warnings from scanners, because the library is no longer patched
- Mixed code styles, since projects were often written over many years
When you work on an old AngularJS app, make small changes, test carefully, and keep notes. This makes a future migration easier.
Exercise
Exercise
Which directive tells AngularJS which part of the page it controls?
