0% found this document useful (0 votes)
715 views33 pages

Angular JS Notes

The document provides an overview of AngularJS, including: 1) AngularJS is a JavaScript framework for building client-side web applications. It was released in 2012 and allows adding dynamic behavior to HTML pages using HTML directives. 2) AngularJS uses directives like ng-app, ng-model and ng-bind to extend HTML and bind data to the HTML view. It also uses expressions delimited by {{ }} to output data in the HTML. 3) AngularJS applications are built using modules, controllers and scopes. Modules define an application, controllers control application logic and scopes provide a link between the HTML and JavaScript.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
715 views33 pages

Angular JS Notes

The document provides an overview of AngularJS, including: 1) AngularJS is a JavaScript framework for building client-side web applications. It was released in 2012 and allows adding dynamic behavior to HTML pages using HTML directives. 2) AngularJS uses directives like ng-app, ng-model and ng-bind to extend HTML and bind data to the HTML view. It also uses expressions delimited by {{ }} to output data in the HTML. 3) AngularJS applications are built using modules, controllers and scopes. Modules define an application, controllers control application logic and scopes provide a link between the HTML and JavaScript.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 33

AngularJS

AngularJS version 1.0 was released in 2012.

Miško Hevery, a Google employee, started to work with AngularJS


in 2009.

AngularJS is a JavaScript framework. It can be added to an


HTML page with a <script> tag.

AngularJS extends HTML attributes with Directives, and binds


data to HTML with Expressions.

 AngularJS is a JavaScript Framework

 AngularJS is a JavaScript framework written in JavaScript.

 AngularJS is distributed as a JavaScript file, and can be


added to a web page with a script tag:

<script src="https://ajax.googleapis.com/ajax/libs/angularjs
/1.6.9/angular.min.js"></script>

 AngularJS Extends HTML

 AngularJS extends HTML with ng-directives.

 The ng-app directive defines an AngularJS application.

 The ng-model directive binds the value of HTML controls


(input, select, textarea) to application data.

 The ng-bind directive binds application data to the HTML


view.
AngularJS Example
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs
/1.6.9/angular.min.js"></script>
<body>

<div ng-app="">
<p>Name: <input type="text" ng-model="name"></p>
<p ng-bind="name"></p>
</div>

</body>
</html>

Example explained:

AngularJS starts automatically when the web page has loaded.

 The ng-app directive tells AngularJS that the <div> element


is the "owner" of an AngularJS application.

 The ng-model directive binds the value of the input field to


the application variable name.

 The ng-bind directive binds the content of the <p> element


to the application variable name.
AngularJS Directives
As you have already seen, AngularJS directives are HTML
attributes with an ng prefix.

 The ng-init directive initializes AngularJS application


variables.

AngularJS Example
<div ng-app="" ng-init="firstName='John'">

<p>The name is <span ng-bind="firstName"></span></p>

</div>

Alternatively with valid HTML:

AngularJS Example
<div data-ng-app="" data-ng-init="firstName='John'">

<p>The name is <span data-ng-bind="firstName"></span></p>

</div>

You can use data-ng-, instead of ng-, if you want to make your
page HTML valid.

AngularJS Expressions
AngularJS expressions are written inside double braces:

{{ expression }}.

AngularJS will "output" data exactly where the expression is


written:
AngularJS Example
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs
/1.6.9/angular.min.js"></script>
<body>

<div ng-app="">
<p>My first expression: {{ 5 + 5 }}</p>
</div>

</body>
</html>

 AngularJS expressions bind AngularJS data to HTML the


same way as the ng-bind directive.

AngularJS Example
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs
/1.6.9/angular.min.js"></script>
<body>

<div ng-app="">
<p>Name: <input type="text" ng-model="name"></p>
<p>{{name}}</p>
</div>

</body>
</html>
AngularJS Applications

AngularJS modules define AngularJS applications.

AngularJS controllers control AngularJS applications.

The ng-app directive defines the application, the ng-


controller directive defines the controller.

AngularJS Example
<div ng-app="myApp" ng-controller="myCtrl">

First Name: <input type="text" ng-model="firstName"><br>


Last Name: <input type="text" ng-model="lastName"><br>
<br>
Full Name: {{firstName + " " + lastName}}

</div>

<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.firstName= "John";
$scope.lastName= "Doe";
});
</script>

AngularJS modules define applications:

AngularJS Module
var app = angular.module('myApp', []);

AngularJS controllers control applications:


AngularJS Controller
app.controller('myCtrl', function($scope) {
$scope.firstName= "John";
$scope.lastName= "Doe";
});
AngularJS Expressions

AngularJS expressions can be written inside double


braces: {{ expression }}.

AngularJS expressions can also be written inside a directive: ng-


bind="expression".

AngularJS will resolve the expression, and return the result


exactly where the expression is written.

AngularJS expressions are much like JavaScript


expressions: They can contain literals, operators, and variables.

Example {{ 5 + 5 }} or {{ firstName + " " + lastName }}

If you remove the ng-app directive, HTML will display the


expression as it is, without solving it

Some example using ng-bind:

Example
<div ng-app="" ng-init="quantity=1;cost=5">

<p>Total in dollar: <span ng-bind="quantity *


cost"></span></p>

</div>
AngularJS strings are like JavaScript strings:
Example
<div ng-app="" ng-init="firstName='John';lastName='Doe'">

<p>The name is {{ firstName + " " + lastName }}</p>

</div>

Same example using ng-bind:

Example
<div ng-app="" ng-init="firstName='John';lastName='Doe'">

<p>The name is <span ng-bind="firstName + ' ' +


lastName"></span></p>

</div>

AngularJS Objects
AngularJS objects are like JavaScript objects:

Example
<div ng-app="" ng-
init="person={firstName:'John',lastName:'Doe'}">

<p>The name is {{ person.lastName }}</p>

</div>
Same example using ng-bind:

Example
<div ng-app="" ng-
init="person={firstName:'John',lastName:'Doe'}">

<p>The name is <span ng-bind="person.lastName"></span></p>

</div>

AngularJS Arrays
AngularJS arrays are like JavaScript arrays:

Example
<div ng-app="" ng-init="points=[1,15,19,2,40]">

<p>The third result is {{ points[2] }}</p>

</div>

Same example using ng-bind:

Example
<div ng-app="" ng-init="points=[1,15,19,2,40]">

<p>The third result is <span ng-bind="points[2]"></span></p>

</div>
AngularJS Modules
An AngularJS module defines an application.

The module is a container for the different parts of an application.

The module is a container for the application controllers.

Controllers always belong to a module.

Creating a Module
A module is created by using the AngularJS
function angular.module

<div ng-app="myApp">...</div>

<script>

var app = angular.module("myApp", []);

</script>

Adding a Controller
Add a controller to your application, and refer to the controller
with the ng-controller directive:

Example
<div ng-app="myApp" ng-controller="myCtrl">
{{ firstName + " " + lastName }}
</div>
<script>

var app = angular.module("myApp", []);

app.controller("myCtrl", function($scope) {
$scope.firstName = "John";
$scope.lastName = "Doe";
});

</script>

AngularJS Directives
AngularJS directives are extended HTML attributes with the
prefix ng-.

The ng-app directive initializes an AngularJS application.

The ng-init directive initializes application data.

The ng-model directive binds the value of HTML controls (input,


select, textarea) to application data.

Repeating HTML Elements

The ng-repeat directive repeats an HTML element:

Example
<div ng-app="" ng-init="names=['Jani','Hege','Kai']">
<ul>
<li ng-repeat="x in names">
{{ x }}
</li>
</ul>
</div>
Create New Directives
In addition to all the built-in AngularJS directives, you can create
your own directives.

New directives are created by using the .directive function.

To invoke the new directive, make an HTML element with the


same tag name as the new directive.

When naming a directive, you must use a camel case


name, w3TestDirective, but when invoking it, you must
use - separated name, w3-test-directive:

Example
<body ng-app="myApp">

<w3-test-directive></w3-test-directive>

<script>
var app = angular.module("myApp", []);
app.directive("w3TestDirective", function() {
return {
template : "<h1>Made by a directive!</h1>"
};
});
</script>

</body>

The ng-model Directive


With the ng-model directive you can bind the value of an input
field to a variable created in AngularJS.

The binding goes both ways. If the user changes the value inside
the input field, the AngularJS property will also change its value:
The ng-model directive can provide type validation for application
data (number, e-mail, required):
If the property in the ng-model attribute does not exist, AngularJS
will create one for you.

The ng-model directive can provide status for application data


(valid, dirty, touched, error):

Example
<form ng-app="" name="myForm" ng-init="myText =
'post@myweb.com'">
Email:
<input type="email" name="myAddress" ng-
model="myText" required>
<h1>Status</h1>
{{myForm.myAddress.$valid}}
{{myForm.myAddress.$dirty}}
{{myForm.myAddress.$touched}}
</form>

The ng-model directive provides CSS classes for HTML elements,


depending on their status

Data binding in AngularJS is the synchronization between the


model and the view.

Two-way Binding
Data binding in AngularJS is the synchronization between the
model and the view.

When data in the model changes, the view reflects the change,
and when data in the view changes, the model is updated as well.
This happens immediately and automatically, which makes sure
that the model and the view is updated at all times.

AngularJS Controllers

AngularJS applications are controlled by controllers.

The ng-controller directive defines the application controller.

A controller is a JavaScript Object, created by a standard


JavaScript object constructor.

AngularJS will invoke the controller with a $scope object.

In AngularJS, $scope is the application object (the owner of


application variables and functions).

Controllers In External Files


In larger applications, it is common to store controllers in
external files.

Just copy the code between the <script> tags into an external file
named personController.js

Example : <script src="personController.js"></script>

AngularJS Scope
The scope is the binding part between the HTML (view) and the
JavaScript (controller).

The scope is an object with the available properties and methods.

The scope is available for both the view and the controller.
How to Use the Scope?

When you make a controller in AngularJS, you pass


the $scope object as an argument:

Example

Properties made in the controller, can be referred to in the view:


<div ng-app="myApp" ng-controller="myCtrl">

<h1>{{carname}}</h1>

</div>

<script>
var app = angular.module('myApp', []);

app.controller('myCtrl', function($scope) {
$scope.carname = "Volvo";
});

</script>

When adding properties to the $scope object in the controller, the


view (HTML) gets access to these properties.

In the view, you do not use the prefix $scope, you just refer to a
property name, like {{carname}}.
Root Scope
All applications have a $rootScope which is the scope created on
the HTML element that contains the ng-app directive.

The rootScope is available in the entire application.

If a variable has the same name in both the current scope and in
the rootScope, the application uses the one in the current scope.

AngularJS Filters
AngularJS provides filters to transform data:

 currency Format a number to a currency format.


 date Format a date to a specified format.
 filter Select a subset of items from an array.
 json Format an object to a JSON string.
 limitTo Limits an array/string, into a specified number of
elements/characters.
 lowercase Format a string to lower case.
 number Format a number to a string.
 orderBy Orders an array by an expression.
 uppercase Format a string to upper case.

Adding Filters to Expressions


Filters can be added to expressions by using the pipe
character |, followed by a filter.

The uppercase filter format strings to upper case:


Example
<div ng-app="myApp" ng-controller="personCtrl">

<p>The name is {{ lastName | uppercase }}</p>

</div>

Adding Filters to Directives


Filters are added to directives, like ng-repeat, by using the pipe
character |, followed by a filter:

Example

The orderBy filter sorts an array:

<div ng-app="myApp" ng-controller="namesCtrl">

<ul>
<li ng-repeat="x in names | orderBy:'country'">
{{ x.name + ', ' + x.country }}
</li>
</ul>

</div>

What is a Service?
In AngularJS, a service is a function, or object, that is available
for, and limited to, your AngularJS application.

AngularJS has about 30 built-in services. One of them is


the $location service.
The $location service has methods which return information
about the location of the current web page:

Example

Use the $location service in a controller:

var app = angular.module('myApp', []);


app.controller('customersCtrl', function($scope, $location)
{
$scope.myUrl = $location.absUrl();
});

The $timeout Service


The $timeout service is AngularJS' version of
the window.setTimeout function.

The $interval Service


The $interval service is AngularJS' version of
the window.setInterval function

AngularJS $http

$http is an AngularJS service for reading data from remote

The AngularJS $http service makes a request to the server, and


returns a response.
Methods
The example above uses the .get method of the $http service.

The .get method is a shortcut method of the $http service. There


are several shortcut methods:

 .delete()
 .get()
 .head()
 .jsonp()
 .patch()
 .post()
 .put()

Properties
The response from the server is an object with these properties:

 .config the object used to generate the request.


 .data a string, or an object, carrying the response from the
server.
 .headers a function to use to get header information.
 .status a number defining the HTTP status.
 .statusText a string defining the HTTP status.

Example
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http) {
$http.get("welcome.htm")
.then(function(response) {
$scope.content = response.data;
$scope.statuscode = response.status;
$scope.statustext = response.statusText;
});
});
http is an XMLHttpRequest object for requesting external data.

AngularJS Tables
The ng-repeat directive is perfect for displaying tables.

Display the Table Index ($index)

To display the table index, add a <td> with $index:

AngularJS Example
<table>
<tr ng-repeat="x in names">
<td>{{ $index + 1 }}</td>
<td>{{ x.Name }}</td>
<td>{{ x.Country }}</td>
</tr>
</table>

Creating a Select Box Using ng-options


If you want to create a dropdown list, based on an object or an
array in AngularJS, you should use the ng-options directive

AngularJS lets you create dropdown lists based on items in an


array, or an object.

The ng-disabled Directive


The ng-disabled directive binds AngularJS application data to
the disabled attribute of HTML elements

The ng-show Directive


The ng-show directive shows or hides an HTML element.
The ng-hide Directive

The ng-hide directive hides or shows an HTML element

AngularJS Events
You can add AngularJS event listeners to your HTML elements by
using one or more of these directives:

 ng-blur
 ng-change
 ng-click
 ng-copy
 ng-cut
 ng-dblclick
 ng-focus
 ng-keydown
 ng-keypress
 ng-keyup
 ng-mousedown
 ng-mouseenter
 ng-mouseleave
 ng-mousemove
 ng-mouseover
 ng-mouseup
 ng-paste

The event directives allows us to run AngularJS functions at


certain user events.

An AngularJS event will not overwrite an HTML event, both events


will be executed.
Mouse Events
Mouse events occur when the cursor moves over an element, in
this order:

1. ng-mouseover
2. ng-mouseenter
3. ng-mousemove
4. ng-mouseleave

Or when a mouse button is clicked on an element, in this order:

1. ng-mousedown
2. ng-mouseup
3. ng-click

Toggle, True/False
If you want to show a section of HTML code when a button is
clicked, and hide when the button is clicked again, like a
dropdown menu, make the button behave like a toggle switch

$event Object
You can pass the $event object as an argument when calling the
function.

The $event object contains the browser's event object:

Example
<div ng-app="myApp" ng-controller="myCtrl">

<h1 ng-mousemove="myFunc($event)">Mouse Over Me!</h1>

<p>Coordinates: {{x + ', ' + y}}</p>


</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.myFunc = function(myE) {
$scope.x = myE.clientX;
$scope.y = myE.clientY;
}
});
</script>

Checkbox
A checkbox has the value true or false. Apply the ng-
model directive to a checkbox, and use its value in your
application.

Example

Show the header if the checkbox is checked:


<form>
Check to show a header:
<input type="checkbox" ng-model="myVar">
</form>

<h1 ng-show="myVar">My Header</h1>

Radiobuttons
Bind radio buttons to your application with the ng-model directive.

Radio buttons with the same ng-model can have different values,
but only the selected one will be used.
AngularJS Form Validation
 AngularJS can validate input data.

 AngularJS offers client-side form validation.

 AngularJS monitors the state of the form and input fields


(input, textarea, select), and lets you notify the user about
the current state.

 AngularJS also holds information about whether they have


been touched, or modified, or not.

 You can use standard HTML5 attributes to validate input, or


you can make your own validation functions.

Client-side validation cannot alone secure user input. Server side


validation is also necessary.

Required
Use the HTML5 attribute required to specify that the input field
must be filled out:

Example

The input field is required:


<form name="myForm">
<input name="myInput" ng-model="myInput" required>
</form>

<p>The input's valid state is:</p>


<h1>{{myForm.myInput.$valid}}</h1>
E-mail
Use the HTML5 type email to specify that the value must be an e-
mail:

Example

The input field has to be an e-mail:


<form name="myForm">
<input name="myInput" ng-model="myInput" type="email">
</form>

<p>The input's valid state is:</p>


<h1>{{myForm.myInput.$valid}}</h1>

Form State and Input State


AngularJS is constantly updating the state of both the form and
the input fields.

Input fields have the following states:

 $untouched The field has not been touched yet


 $touched The field has been touched
 $pristine The field has not been modified yet
 $dirty The field has been modified
 $invalid The field content is not valid
 $valid The field content is valid

They are all properties of the input field, and are


either true or false.

Forms have the following states:


 $pristine No fields have been modified yet
 $dirty One or more have been modified
 $invalid The form content is not valid
 $valid The form content is valid
 $submitted The form is submitted

They are all properties of the form, and are either true or false.

AngularJS Global API

The AngularJS Global API is a set of global JavaScript functions


for performing common tasks like:

 Comparing objects
 Iterating objects
 Converting data

The Global API functions are accessed using the angular object.

Below is a list of some common API functions:

API Description

angular.lowercase() Converts a string to lowercase

angular.uppercase() Converts a string to uppercase

angular.isString() Returns true if the reference is a string

angular.isNumber() Returns true if the reference is a number


 With AngularJS, you can include HTML from an external file.

AngularJS Includes
With AngularJS, you can include HTML content using the ng-
include directive:

Example
<body ng-app="">

<div ng-include="'myFile.htm'"></div>

</body>

Include Cross Domains

By default, the ng-include directive does not allow you to


include files from other domains.

To include files from another domain, you can add a whitelist of


legal files and/or domains in the config function of your
application:

Example :

<body ng-app="myApp">

<div ng-
include="'https://tryit.w3schools.com/angular_include.php'">
</div>

<script>
var app = angular.module('myApp', [])
app.config(function($sceDelegateProvider) {
$sceDelegateProvider.resourceUrlWhitelist([
'https://tryit.w3schools.com/**'
]);
});

</script>

</body>
AngularJS Animations

AngularJS provides animated transitions, with help from CSS.

What is an Animation?

An animation is when the transformation of an HTML element


gives you an illusion of motion.

Example:

Check the checkbox to hide the DIV:


<body ng-app="ngAnimate">

Hide the DIV: <input type="checkbox" ng-model="myCheck">

<div ng-hide="myCheck"></div>

</body>

Applications should not be filled with animations, but some


animations can make the application easier to understand.
What do I Need?

 To make your applications ready for animations, you must


include the AngularJS Animate library:

<script src="https://ajax.googleapis.com/ajax/libs/angularjs
/1.6.9/angular-animate.js"></script>

 Then you must refer to the ngAnimate module in your


application:

<body ng-app="ngAnimate">

 Or if your application has a name, add ngAnimate as a


dependency in your application module:

Example
<body ng-app="myApp">

<h1>Hide the DIV: <input type="checkbox" ng-


model="myCheck"></h1>

<div ng-hide="myCheck"></div>

<script>
var app = angular.module('myApp', ['ngAnimate']);

</script>
What Does ngAnimate Do?

The ngAnimate module adds and removes classes.

The ngAnimate module does not animate your HTML elements,


but when ngAnimate notice certain events, like hide or show of
an HTML element, the element gets some pre-defined classes
which can be used to make animations.

The directives in AngularJS who add/remove classes are:

 ng-show
 ng-hide
 ng-class
 ng-view
 ng-include
 ng-repeat
 ng-if
 ng-switch

The ng-show and ng-hide directives adds or removes a ng-


hide class value.

The other directives adds a ng-enter class value when they enter
the DOM, and a ng-leave attribute when they are removed from
the DOM.

The ng-repeat directive also adds a ng-move class value when the
HTML element changes position.

In addition, during the animation, the HTML element will have a


set of class values, which will be removed when the animation
has finished. Example: the ng-hide directive will add these class
values:

 ng-animate
 ng-hide-animate
 ng-hide-add (if the element will be hidden)
 ng-hide-remove (if the element will be showed)
 ng-hide-add-active (if the element will be hidden)
 ng-hide-remove-active (if the element will be showed)

Animations Using CSS

We can use CSS transitions or CSS animations to animate HTML


elements. This tutorial will show you both.

CSS Transitions

CSS transitions allows you to change CSS property values


smoothly, from one value to another, over a given duration:

Example:

When the DIV element gets the .ng-hide class, the transition will
take 0.5 seconds, and the height will smoothly change from
100px to 0:
<style>
div {
transition: all linear 0.5s;
background-color: lightblue;
height: 100px;
}

.ng-hide {
height: 0;
}
</style>
CSS Animations

CSS Animations allows you to change CSS property values


smoothly, from one value to another, over a given duration:

Example:

When the DIV element gets the .ng-hide class,


the myChange animation will run, which will smoothly change the
height from 100px to 0:
<style>
@keyframes myChange {
from {
height: 100px;
} to {
height: 0;
}
}

div {
height: 100px;
background-color: lightblue;
}

div.ng-hide {
animation: 0.5s myChange;
}
</style>
AngularJS Routing

 The ngRoute module helps your application to become a


Single Page Application.

What is Routing in AngularJS?


If you want to navigate to different pages in your application, but
you also want the application to be a SPA (Single Page
Application), with no page reloading, you can use
the ngRoute module.

The ngRoute module routes your application to different pages


without reloading the entire application

What do I Need?
 To make your applications ready for routing, you must
include the AngularJS Route module:

<script src="https://ajax.googleapis.com/ajax/libs/angularjs
/1.6.9/angular-route.js"></script>

 Then you must add the ngRoute as a dependency in the


application module:

var app = angular.module("myApp", ["ngRoute"]);


 Now your application has access to the route module, which
provides the $routeProvider.

 Use the $routeProvider to configure different routes in your


application:

app.config(function($routeProvider) {
$routeProvider
.when("/", {
templateUrl : "main.htm"
})
.when("/red", {
templateUrl : "red.htm"
})
.when("/green", {
templateUrl : "green.htm"
})
.when("/blue", {
templateUrl : "blue.htm"
});
});
$routeProvider

With the $routeProvider you can define what page to display


when a user clicks a link.

Template

You can also use the template property, which allows you to write
HTML directly in the property value, and not refer to a page.

The otherwise method

You can also use the otherwise method, which is the default route
when none of the others get a match.

You might also like