0% found this document useful (0 votes)
24 views50 pages

WEBX Module3

Module III provides an introduction to AngularJS, covering its core features, advantages, and disadvantages, as well as its architecture based on the Model View Controller (MVC) pattern. It explains key concepts such as directives, data binding, controllers, filters, and dependency injection, along with practical examples for creating AngularJS applications. The document emphasizes AngularJS's capability to build single-page applications and its cross-browser compatibility.

Uploaded by

leken52079
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
24 views50 pages

WEBX Module3

Module III provides an introduction to AngularJS, covering its core features, advantages, and disadvantages, as well as its architecture based on the Model View Controller (MVC) pattern. It explains key concepts such as directives, data binding, controllers, filters, and dependency injection, along with practical examples for creating AngularJS applications. The document emphasizes AngularJS's capability to build single-page applications and its cross-browser compatibility.

Uploaded by

leken52079
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 50

Module III

INTRODUCTION TO ANGULARJS
CO3: Build single page applications with AngularJS
Contents:
 Overview of AngularJS
 Need of AngularJS in real web sites
 AngularJS Modules
 AngularJS built-in directives
 AngularJS custom directives
 AngularJS expression
 AngularJS data binding
 AngularJS filters
 AngularJS controllers
 AngularJS scope
 AngularJS dependency injection
 AngularJS services
 Form validation
 Routing using ng-route,ng-repeat,ng-style,ng-view using anglarJS with Typescript
AngularJS Overview

AngularJS is an open-source web application framework. It was originally developed in 2009 by Misko
Hevery and Adam Abrons. It is now maintained by Google. Its latest version is 1.8.3
• AngularJS is a efficient framework that can create Rich Internet Applications (RIA).
• AngularJS provides developers an options to write client side applications using JavaScript
in a clean Model View Controller (MVC) way.
• Applications written in AngularJS are cross-browser compliant. AngularJS automatically
handles JavaScript code suitable for each browser.
• AngularJS is open source, completely free, and used by thousands of developers around the
world. It is licensed under the Apache license version 2.0.
Overall, AngularJS is a framework to build large scale, high-performance, and easy to-maintain web
applications.
Core Features

• Data-binding − It is the automatic synchronization of data between model and view components.
• Scope − These are objects that refer to the model. They act as a glue between controller and view.
• Controller − These are JavaScript functions bound to a particular scope.
• Services − AngularJS comes with several built-in services such as $http to make a XMLHttpRequests.
These are singleton objects which are instantiated only once in app.
• Filters − These select a subset of items from an array and returns a new array.
• Directives − Directives are markers on DOM elements such as elements, attributes, css, and more.
These can be used to create custom HTML tags that serve as new, custom widgets. AngularJS has built-
in directives such as ngBind, ngModel, etc.
• Templates − These are the rendered view with information from the controller and model. These can
be a single file (such as index.html) or multiple views in one page using partials.
Core Features

• Routing − It is concept of switching views.


• Model View Whatever − MVW is a design pattern for dividing an application into different parts called Model,
View, and Controller, each with distinct responsibilities. AngularJS does not implement MVC in the traditional
sense, but rather something closer to MVVM (Model-View-ViewModel). The Angular JS team refers it humorously
as Model View Whatever.
• Deep Linking − Deep linking allows to encode the state of application in the URL so that it can be bookmarked.
The application can then be restored from the URL to the same state.
• Dependency Injection − AngularJS has a built-in dependency injection subsystem that helps the developer to
create, understand, and test the applications easily.
Advantages of AngularJS

• It provides the capability to create Single Page Application in a very clean and maintainable way.
• It provides data binding capability to HTML. Thus, it gives user a rich and responsive experience.
• AngularJS code is unit testable.
• AngularJS uses dependency injection and make use of separation of concerns.
• AngularJS provides reusable components.
• With AngularJS, the developers can achieve more functionality with short code.
• In AngularJS, views are pure html pages, and controllers written in JavaScript do the business
processing.
**On the top of everything, AngularJS applications can run on all major browsers and smart phones,
including Android and iOS based phones/tablets.
Disadvantages of AngularJS

• Not Secure − Being JavaScript only framework, application written in AngularJS are not safe.
Server side authentication and authorization is must to keep an application secure.

• Not degradable − If the user of your application disables JavaScript, then nothing would be
visible, except the basic page.
MVC Model

 Model View Controller or MVC as it is popularly called, is a software design pattern for
developing web applications. A Model View Controller pattern is made up of the following
three parts −
• Model − It is the lowest level of the pattern responsible for maintaining data.
• View − It is responsible for displaying all or a portion of the data to the user.
• Controller − It is a software Code that controls the interactions between the Model and
View.
Directives in AngularJS:

 An AngularJS application consists of following three important parts −

• ng-app − This directive defines and links an AngularJS application to HTML.


• ng-model − This directive binds the values of AngularJS application data to HTML input controls
(input,select,textarea).
• ng-bind − This directive binds the AngularJS Application data to HTML tags.
Some more directives:
• ng-init directives initializes application data
• ng-repeat directive repeats an HTML element. Ng-repeat directive actually clones HTML elements
once for each item in a collection.ng-repeat directive used on an array of objects.
DOM
Creating AngularJS Application

 Step 1: Load framework


Being a pure JavaScript framework, it can be added using <Script> tag.
<script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js">
</script>
 Step 2: Define AngularJS application using ng-app directive
<div ng-app = "">
...
</div>
 Step 3: Define a model name using ng-model directive
<p>Enter your Name: <input type = "text" ng-model = "name"></p>

 Step 4: Bind the value of above model defined using ng-bind directive
<p>Hello <span ng-bind = "name"></span>!</p>
How AngularJS Integrates with HTML

• The ng-app directive indicates the start of AngularJS application.


• The ng-model directive creates a model variable named name, which can be used with the HTML page
and within the div having ng-app directive.
• The ng-bind then uses the name model to be displayed in the HTML <span> tag whenever user enters
input in the text box.
• Closing</div> tag indicates the end of AngularJS application.
AngularJS - Expressions

 Expressions are used to bind application data to HTML.


 Expressions are written inside double curly braces such as in {{ expression}}.
 Expressions behave similar to ng-bind directives. It contains literals, operators and variables.
1. Using numbers
<p>Expense on Books : {{cost * quantity}} Rs</p>

2. Using Strings
<p>Hello {{student.firstname + " " + student.lastname}}!</p>

3. Using Object
<p>Roll No: {{student.rollno}}</p>

4. Using Array
<p>Marks(Math): {{marks[3]}}</p>
AngularJS - Controllers

 AngularJS application mainly relies on controllers to control the flow of data in the application.
 A controller is defined using ng-controller directive.
 A controller is a JavaScript object that contains attributes/properties, and functions. Each controller
accepts $scope as a parameter, which refers to the application/module that the controller needs to
handle.
1. Here, we declare a controller named studentController, using the ng-controller directive
2. We define it as follows −
3. Now we can use studentController's student property using ng-model or using expressions
as follows −

Note-
•We bound student.firstName and student.lastname to two input boxes.
•We bound student.fullName() to HTML.
•Now whenever you type anything in first name and last name input boxes, you can see the full name getting
updated automatically.
AngularJS - Filters

❖ Filters are used to modify the data.


❖ They can be clubbed in expression or directives using pipe (|) character.
The following list shows the commonly used filters.
Sr.No. Name & Description
1 uppercase converts a text to upper case text.

2 lowercase converts a text to lower case text.

3 currency formats text in a currency format.

4 filter filter the array to a subset of it based on provided criteria.

5 orderby orders the array based on provided criteria.


❖ Uppercase filter (Add uppercase filter to an expression using pipe character)

❖ Lowercase Filter

❖ Currency Filter Add currency filter to an expression returning number using pipe character

❖ OrderBy Filter
AngularJS modules

 AngularJS supports modular approach.


 Modules are used to separate logic such as services, controllers, application etc. from the code and
maintain the code clean.
 We define modules in separate js files and name them as per the module.js file.
In the following example, we are going to create two modules −
1. Application Module − used to initialize an application with controller(s).
2. Controller Module − used to define the controller.
1. Application Module

Here is a file named mainApp.js that contains the following code −

Here, we declare an application mainApp module using angular.module function and pass an empty array
to it. This array generally contains dependent modules.
2. Controller Module

studentController.js

Here, we declare a controller studentController module using mainApp.controller


function.
 Use Modules

Here, we use application module using ng-app directive, and controller using ng-controller directive. We import the
mainApp.js and studentController.js in the main HTML page

For Example :
<html>
<head>
<title>AngularJS Directives</title>
</head>
<body>
<h1>Sample Application</h1>
<div ng-app = "" ng-init = "countries = [{locale:'en-US',name:'United States'},
{locale:'en-GB',name:'United Kingdom'}, {locale:'en-FR',name:'France'}]">
<p>Enter your Name: <input type = "text" ng-model = "name"></p>
<p>Hello <span ng-bind = "name"></span>!</p>
<p>List of Countries with locale:</p>
<ol>
<li ng-repeat = "country in countries">
{{ 'Country: ' + country.name + ', Locale: ' + country.locale }}
</li>
</ol>
</div>
<script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js">
</script>
</body>
</html>
AngularJS scope

 Scope is a special JavaScript object that connects controller with views.


Scope contains model data. In controllers, model data is accessed via
$scope object.
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.

Understanding the Scope


If we consider an AngularJS application to consist of:
• View, which is the HTML.
• Model, which is the data available for the current view.
• Controller, which is the JavaScript function that makes/changes/removes/controls the data.
Then the scope is the Model.
So, The scope is a JavaScript object with properties and methods, which are 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 of Scope:
<div ng-app="myApp" ng-controller="myCtrl">

<input ng-model="name">

<h1>My name is {{name}}</h1>

</div>

<script>

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

app.controller('myCtrl', function($scope)
{
$scope.name = “Pragati Patil";
});

</script>
Dependency Injection

 Dependency Injection is a software design pattern


 Components are given their dependencies no values.
 Makes Dependencies configurable.
 Make Components reusable, maintainable and testable
Example code
With Dependency Injection
Without Dependency Injection
Var employee = function
Var employee = function (empName,designation){
(empName,designation){
this.empName=empName;
this.empName=empName; this.designation=designation;
this.designation=designation; }
} function addEmp(emp){
function addEmp(){ //code
var emp = new employee(“John” , }
“Manager”); var emp = new employee(“John” , “Manager”);
} }
addEmp(); addEmp(emp);
Dependency Injection in AngularJS

In AngularJS, dependency injection can be implemented in following ways:

• Value
• Factory
• Service
• Provider
• Constant
Value:
Value is a simple JavaScript object, which is required to pass values to the controller during config phase
(config phase is when AngularJS bootstraps itself).
Factory:
Factory is a function which is used to return value. It creates a value on demand whenever a service or a
controller requires it. It generally uses a factory function to calculate and return the value.
Service:
Service is a singleton JavaScript object containing a set of functions to perform certain tasks. Service is
defined using service() function and it is then injected into the controllers.
Provider:
Provider is used by AngularJS internally to create services, factory, etc. during the config phase. The
following script can be used to create MathService that we created earlier. Provider is a special factory
method with get() method which is used to return the value/service/factory.
Constant:
Constants are used to pass values at the config phase considering the fact that value cannot be used
during the config phase.
mainApp.constant("configParam", "constant value");
<html><head>  mainApp.value("defaultInput", 5);
<title>AngularJS Dependency Injection</title></head>  mainApp.factory('MathService', function() {
<body><h2>AngularJS Sample Application</h2>
 var factory = {};
<div ng-app = "mainApp" ng-controller = "CalcController">  factory.multiply = function(a, b) {
<p>Enter a number: <input type = "number" ng-model =  return a * b;
"number" /> </p>
<button ng-click = "square()">X<sup>2</sup> </button>  }
<p>Result: {{result}}</p> </div>  return factory;
<script src =
 });
"https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js">
</script>  mainApp.service('CalcService', function(MathService)
<script> {
var mainApp = angular.module("mainApp", []);  this.square = function(a) {
 return MathService.multiply(a,a);
mainApp.config(function($provide) {
 } });
$provide.provider('MathService', function() {  mainApp.controller('CalcController', function($scope,
this.$get = function() { CalcService, defaultInput) {
var factory = {};  $scope.number = defaultInput;
factory.multiply = function(a, b) {
return a * b;  $scope.result = CalcService.square($scope.number);
}
$scope.square = function() {
return factory;  $scope.result =
}; CalcService.square($scope.number);
});  } });
});
 </script> </body></html>
AngularJS Services
 AngularJS provides many inbuilt services.
 For example, $http, $route, $window, $location, etc.
 Each service is responsible for a specific task such as the
 $http is used to make ajax call to get the server data,
 the $route is used to define the routing information, and so on.
 The inbuilt services are always prefixed with $ symbol.
There are two ways to create a service −
• Factory
Factory is a function which is used to return value. It creates a value on demand whenever a service or a
controller requires it. It generally uses a factory function to calculate and return the value
• Service
• Service is a singleton JavaScript object containing a set of functions to perform certain tasks.
Service is defined using service() function and it is then injected into the controllers.
AngularJS Forms

 AngularJS facilitates you to create a form enriches with data binding and
validation of input controls.
 Input controls are ways for a user to enter data. A form is a collection of controls
for the purpose of grouping related controls together.
Following are the input controls used in AngularJS forms:
• input elements
• select elements
• button elements
• textarea elements
Events

Usually ng-click directive is generally associated with a button. AngularJS supports the following events
• ng-click
• ng-dbl-click
• ng-mousedown
• ng-mouseup
• ng-mouseenter
• ng-mouseleave
• ng-mousemove
• ng-mouseover
• ng-keydown
• ng-keyup
• ng-keypress
• ng-change
 AngularJS Checkbox
A checkbox has a value true or false. The ng-model directive is used for a checkbox.
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>
<div ng-app="">
<form>
Check to show a header:
<input type="checkbox" ng-model="myVar">
</form>
<h1 ng-show="myVar">My Header</h1>
</div>

<p>The header's ng-show attribute is set to true when the checkbox is checked.</p>

</body>
</html>
AngularJS Radio Buttons
 ng-model directive is used to bind radio buttons in your applications
<html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body ng-app="">
<div ng-switch-when="fest">
<form>
<h1>Festivals</h1>
Pick a topic: <p>Most famous festivals</p>
<input type="radio" ng-model="myVar" value="tuts">Tutorials </div>
<input type="radio" ng-model="myVar" value="fest">Festivals <div ng-switch-when="news">
<input type="radio" ng-model="myVar" value="news">News <h1>News</h1>
</form> <p>Welcome to the news portal.</p>
<div ng-switch="myVar">
</div>
</div>
<div ng-switch-when="tuts">
<p>The ng-
<h1>Tutorials</h1> switch directive hides and shows HTML secti
<p>Welcome to the best tutorials over the net</p> </div> ons depending on the value of the radio butto
ns.</p>
</div> </body>
</html>
Form Validation
 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
 Note: Client-side validation cannot alone secure user input. Server-side validation is also necessary.

Following directives are generally used to track errors in an AngularJS form:


• $dirty - states that value has been changed.
• $invalid - states that value entered is invalid.
• $error - states the exact error.
<form ng-app="myApp" ng-controller="validateCtrl" name="myForm" novalidate>
<p>Username:<br>
<input type="text" name="user" ng-model="user" required>
<span style="color:red" ng-show="myForm.user.$dirty && myForm.user.$invalid">
<span ng-show="myForm.user.$error.required">Username is required.</span>
</span></p>

<p>Email:<br>
<input type="email" name="email" ng-model="email" required>
<span style="color:red" ng-show="myForm.email.$dirty && myForm.email.$invalid">
<span ng-show="myForm.email.$error.required">Email is required.</span>
<span ng-show="myForm.email.$error.email">Invalid email address.</span>
</span>
</p>

<p><input type="submit“ ng-disabled="myForm.user.$dirty && myForm.user.$invalid ||


myForm.email.$dirty && myForm.email.$invalid"></p>
</form>
<script>
var app = angular.module('myApp', []);
app.controller('validateCtrl', function($scope) {
$scope.user = 'John Doe';
$scope.email = '[email protected]';
});
</script>
Routing
.

 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
 Step-1
Step -2
With the $routeProvider you can define what page to display when a user clicks a link
Step-3
 Your application needs a container to put the content provided by the routing.
This container is the ng-view directive.
 There are three different ways to include the ng-view directive in your application:
1. <div ng-view></div>
2. <ng-view></ng-view>
3. <div class="ng-view"></div>

You might also like