Unit 2 WT
Unit 2 WT
Fundamentals of Angular JS and NODE JS Angular Java Script- Introduction to Angular JS Expressions:
ARRAY, Objects, Strings, Angular JS Form Validation & Form Submission. Node.js- Introduction,
Advantages, Node.js Process Model, Node JS Modules, Node JS File system, Node JS URL module, Node
JS Events.
Introduction to Angular JS
AngularJS is an open source JavaScript MVC framework for web application or web sites.
It extends the HTML and makes it dynamic. AngularJS can be used to create Single Page
Applications.
AngularJS was originally started as a project in Google but now, it is open source
framework.
AngularJS is entirely based on HTML and JavaScript, so there is no need to learn another
syntax or language.
AngularJS changes static HTML to dynamic HTML.
It extends the ability of HTML by adding built-in attributes and components and also
provides an ability to create custom attributes using simple JavaScript.
Advantages of AngularJS
Open source JavaScript MVC framework.
Supported by Google
No need to learn another scripting language. It's just pure JavaScript and HTML.
Supports separation of concerns by using MVC design pattern.
Built-in attributes (directives) makes HTML dynamic.
Easy to extend and customize.
Supports Single Page Application.
Uses Dependency Injection.
Easy to Unit test.
REST friendly.
AngularJS Expression
AngularJS expression is like JavaScript expression surrounded with braces - {{ expression }}. AngularJS
evaluates the specified expression and binds the result data to HTML.
Example: Expression
<!DOCTYPE html>
<html >
<head>
<script src="~/Scripts/angular.js"></script>
</head>
<body >
<h1>AngularJS Expression Demo:</h1>
<div ng-app>
2 + 2 = {{2 + 2}} <br />
2 - 2 = {{2 - 2}} <br />
2 * 2 = {{2 * 2}} <br />
2 / 2 = {{2 / 2}}
</div>
</body>
</html>
Result:
2 + 2 = 4
2 - 2 = 0
2 * 2 = 4
2 / 2 = 1
AngularJS expression is like JavaScript code expression except for the following differences:
Example: Expression
<html >
<head>
<script src="~/Scripts/angular.js"></script>
</head>
<body >
AngularJS Arrays
Expressions can be used to work with arrays as well. Let’s look at an example of Angular JS expressions
with arrays.
In this example, we are going to define an array which is going to hold the marks of a student in 3
subjects. In the view, we will display the value of these marks accordingly.
<!DOCTYPE html>
<html>
<head>
<meta chrset="UTF 8">
<title>Event Registration</title>
</head>
<body>
<script src="https://code.angularjs.org/1.6.9/angular-route.js"></script>
<script src="https://code.angularjs.org/1.6.9/angular.min.js"></script>
<h1> VITW</h1>
Student Marks<br>
Subject1 : {{marks[0] }}<br>
Subject2 : {{marks[1] }}<br>
Subject3 : {{marks[2] }}<br>
</div>
</body>
</html>
The ng-init directive is used define the array with the name “marks” with 3 values of 1, 15 and
19.
We are then using expressions of marks [index] to access each element of the array.
If the code is executed successfully, the following Output will be shown when you run your code
in the browser.
OUTPUT:
Student Marks
Subject1 : 1
Subject2 : 15
Subject3 :19
Angular.JS Objects
Expressions can be used to work with JavaScript objects as well.
Let’s look at an example of Angular.JS expressions with javascript objects. A javascript object
consists of a name-value pair.
Syntax:
In this example, we are going to define one object as a person object which will have 2 key value pairs of
“firstName” and “lastName”.
EXAMPLE CODE:
<!DOCTYPE html>
<html>
<head>
<meta chrset="UTF 8">
<title>Event Registration</title>
</head>
<body>
<script src="https://code.angularjs.org/1.6.9/angular-route.js"></script>
First Name : {{person.firstName}}<br>
Last Name : {{person.lastName}}
</div>
</body>
</html>
Code Explanation:
The ng-init directive is used to define the object person which in turn has key value pairs of
firstName with the value “SHALINI” and the variable lastName with the value of “TAMMANA”.
We are then using expressions of {{person.firstName}} and {{person.secondName}} to access the
value of these variables and display them in the view accordingly. Since the actual member
variables are part of the object person, they have to access it with the dot (.) notation to access
their actual value.
If the code is executed successfully, the following Output will be shown when you run your code in the
browser.
OUTPUT:
WELCOME TO EVENT
firstName: SHALINI
lastName: TAMMANA
AngularJS Strings
Expressions can be used to work with strings as well. Let’s look at an example of Angular JS
expressions with strings.
In this example, we are going to define 2 strings of “firstName” and “lastName” and display
them using expressions accordingly.
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<script src="https://code.angularjs.org/1.6.9/angular-route.js"></script>
<script src="https://code.angularjs.org/1.6.9/angular.min.js"></script>
First Name : {{firstName}}<br>
last Name : {{lastName}}
</div>
</body>
</html>
Code Explanation:
The ng-init directive is used define the variables firstName with the value “Guru” and the
variable lastName with the value of “99”.
We are then using expressions of {{firstName}} and {{lastName}} to access the value of these
variables and display them in the view accordingly.
If the code is executed successfully, the following Output will be shown when you run your code in the
browser.
Output:
GLOBAL EVENT
firstName: SHALINI
lastName: TAMMANA
Validation in AngularJS
We created an HTML form in the previous section. Here, we will implement client side validation in
AngularJS form.
Directive Description
ng- Sets maxlength attribute on an input field. Setting the attribute to a negative or non-numeric value, allows v
maxlength length.
ng-pattern Sets pattern validation error key if the ngModel value does not match the specified RegEx expression.
Let's implement validation in the student form which contains First Name, Last Name and Email fields.
<!DOCTYPE html>
<html>
<head>
<script src="~/Scripts/angular.js"></script>
</head>
<body ng-app >
<form name="studentForm" novalidate>
<label for="firstName">First Name: </label> <br />
<input type="text" name="firstName" ng-
model="student.firstName" ng-required="true" />
<span ng-show="studentForm.firstName.$touched &&
studentForm.firstName.$error.required">First name is
required.</span><br /><br />
<label for="lastName">Last Name</label><br />
Apply novalidate attribute in <form> tag. The novalidate attribute will disable the browser's
default validation.
Set the name attribute in <form> and other elements, which will be used to obtain a reference
of the elements.
AngularJS Forms
The HTML form is a collection of input controls where user can enter the data. Here, you will
learn how to display AngularJS form and submit the data.
An AngularJS Form Example
We will create following Student Information form with submit and reset functionality.
<!DOCTYPE html>
<html ng-app="studentApp">
<head>
<script src="~/Scripts/angular.js"></script>
</head>
<body ng-controller="studentController">
<h1>Student Information:</h1>
<form ng-submit="submitStudnetForm()" >
<label for="firstName" >First Name: </label><br />
<input type="text" id="firstName" ng-
model="student.firstName" /> <br />
$http.post('/student/submitData', { student:
$scope.student })
.success(onSuccess)
.error(onError);
};
Output:
Create an HTML page and wrap all the necessary input controlls into <form> tag.
Create the AngularJS application module in the <script> tag.
Create studentController in application module.
Create originalStudent object and attach to the $scope with required properties. This will stay
unchanged during entire life cycle.
Create new student object and attach to the $scope and copy all the properties and values from
originalStudent. This student object will be bound to the form using ng-model directive.
Therefore, if user changes form values then the student object will also get changed.
Create submitStudnetForm function which will get called when user submits the form using
Submit button. Here, send http POST request to the remote server to submit the data
using $http service.
Create resetForm() function, which will reset the form values to the originalStudent values by
copying it to student object.
Apply ng-app, ng-controller directives.
Apply ng-model directives to each HTML input element to bind appropriate properties of
student object.
Apply ng-submit directive to form which will call submitStudentForm() on the form submit
event.
Apply ng-click directive to reset button which will call resetForm() on the button click event.
An AngularJS form can be submitted using either ng-submit or ng-click directive but not both.
Ng-submit: Binds angular expression to onsubmit event when form does not include action attribute.
Introduction:
Node.js is an open source, cross-platform runtime environment for developing server-side and
networking applications. Node.js applications are written in JavaScript, and can be run within
the Node.js runtime on OS X, Microsoft Windows, and Linux.
Node.js also provides a rich library of various JavaScript modules which simplifies the
development of web applications using Node.js to a great extent.
Features of Node.js
Following are some of the important features that make Node.js the first choice of software architects.
Asynchronous and Event Driven − All APIs of Node.js library are asynchronous, that is, non-
blocking. It essentially means a Node.js based server never waits for an API to return data. The
server moves to the next API after calling it and a notification mechanism of Events of Node.js
helps the server to get a response from the previous API call.
Very Fast − Being built on Google Chrome's V8 JavaScript Engine, Node.js library is very fast in
code execution.
Single Threaded but Highly Scalable − Node.js uses a single threaded model with event looping.
Event mechanism helps the server to respond in a non-blocking way and makes the server highly
scalable as opposed to traditional servers which create limited threads to handle requests.
Node.js uses a single threaded program and the same program can provide service to a much
larger number of requests than traditional servers like Apache HTTP Server.
No Buffering − Node.js applications never buffer any data. These applications simply output the
data in chunks.
ADVANTAGES:
Efficient performance.
Easier development process.
Reusable code.
Ability to handle multiple requests.
Ability to scale smoothly.
Prompt code execution.
Asynchronous and event-driven.
Supported by leading companies.
An event loop is constantly watching for the events to be raised for an asynchronous job and executing
callback function when the job completes. Internally, Node.js uses libev for the event loop which in turn
uses internal C++ thread pool to provide asynchronous I/O.
The following figure illustrates asynchronous web server model using Node.js.
Built-in Modules
Node.js has a set of built-in modules which you can use without any further installation.
Include Modules
var http = require('http');
Now your application has access to the HTTP module, and is able to create a server:
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.end('Hello World!');
}).listen(8080);
You can create your own modules, and easily include them in your applications.
The following example creates a module that returns a date and time object:
Example
Use the exports keyword to make properties and methods available outside the module file.
Now you can include and use the module in any of your Node.js files.
Example
Use the module "myfirstmodule" in a Node.js file:
var http = require('http');
var dt = require('./myfirstmodule');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write("The date and time are currently: " + dt.myDateTime());
res.end();
}).listen(8080);
var fs = require('fs');
Read files
Create files
Update files
Delete files
Rename files
Read Files
The fs.readFile() method is used to read files on your computer.
Assume we have the following HTML file (located in the same folder as Node.js):
demofile1.html
<html>
<body>
<h1>My Header</h1>
<p>My paragraph.</p>
</body>
</html>
Create a Node.js file that reads the HTML file, and return the content:
Example
var http = require('http');
var fs = require('fs');
http.createServer(function (req, res) {
Save the code above in a file called "demo_readfile.js", and initiate the file:
Initiate demo_readfile.js:
Create Files
The File System module has methods for creating new files:
fs.appendFile()
fs.open()
fs.writeFile()
var fs = require('fs');
fs.appendFile('mynewfile1.txt', 'Hello content!', function (err) {
if (err) throw err;
console.log('Saved!');
});
Example
Create a new, empty file using the open() method:
var fs = require('fs');
fs.open('mynewfile2.txt', 'w', function (err, file) {
if (err) throw err;
console.log('Saved!');
});
Example
Create a new file using the writeFile() method:
var fs = require('fs');
fs.writeFile('mynewfile3.txt', 'Hello content!', function (err) {
if (err) throw err;
console.log('Saved!');
});
fs.appendFile()
fs.writeFile()
Example
Append "This is my text." to the end of the file "mynewfile1.txt":
var fs = require('fs');
Example
Replace the content of the file "mynewfile3.txt":
var fs = require('fs');
fs.writeFile('mynewfile3.txt', 'This is my text', function (err) {
if (err) throw err;
console.log('Replaced!');
});
Example
Delete "mynewfile2.txt":
var fs = require('fs');
fs.unlink('mynewfile2.txt', function (err) {
if (err) throw err;
console.log('File deleted!');
});
Rename Files
To rename a file with the File System module, use the fs.rename() method.
Example
Rename "mynewfile1.txt" to "myrenamedfile.txt":
var fs = require('fs');
fs.rename('mynewfile1.txt', 'myrenamedfile.txt', function (err) {
if (err) throw err;
console.log('File Renamed!');
});
Node.js URL Module
var url = require('url');
Example
Split a web address into readable parts:
var url = require('url');
var adr = 'http://localhost:8080/default.htm?year=2017&month=february';
var q = url.parse(adr, true);
console.log(q.host); //returns 'localhost:8080'
console.log(q.pathname); //returns '/default.htm'
console.log(q.search); //returns '?year=2017&month=february'
Create two html files and save them in the same folder as your node.js files.
summer.html
<!DOCTYPE html>
<html>
<body>
<h1>Summer</h1>
<p>I love the sun!</p>
</body>
</html>
winter.html
<!DOCTYPE html>
<html>
<body>
<h1>Winter</h1>
<p>I love the snow!</p>
</body>
</html>
Create a Node.js file that opens the requested file and returns the content to
the client. If anything goes wrong, throw a 404 error:
demo_fileserver.js:
var http = require('http');
var url = require('url');
var fs = require('fs');
http.createServer(function (req, res) {
var q = url.parse(req.url, true);
var filename = "." + q.pathname;
fs.readFile(filename, function(err, data) {
if (err) {
res.writeHead(404, {'Content-Type': 'text/html'});
return res.end("404 Not Found");
Initiate demo_fileserver.js:
If you have followed the same steps on your computer, you should see two
different results when opening these two addresses:
http://localhost:8080/summer.html
Summer
I love the sun!
http://localhost:8080/winter.html
Winter
I love the snow!
Node.js Events
Node.js is perfect for event-driven applications.
Objects in Node.js can fire events, like the readStream object fires events when
opening and closing a file:
Example
var fs = require('fs');
var rs = fs.createReadStream('./demofile.txt');
rs.on('open', function () {
console.log('The file is open');
});
Events Module
Node.js has a built-in module, called "Events", where you can create-, fire-, and
listen for- your own events.
var events = require('events');
var eventEmitter = new events.EventEmitter();
Example
var events = require('events');
var eventEmitter = new events.EventEmitter();