0% found this document useful (0 votes)
9 views154 pages

Overview of AngularJS Framework Features

Uploaded by

Nikshitha R s
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)
9 views154 pages

Overview of AngularJS Framework Features

Uploaded by

Nikshitha R s
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

What Is Angular JS?

Angular JS is an open source Model-View-Controller framework


which is similar to the JavaScript framework.

It is one of the most popular modern day web frameworks


available today.

This framework is used for developing Single Page


Applications.

DEPARTMRNT OF MCA 3
Cont…

This framework has been developed by a group of developers from


Google itself.

Because of the sheeper support of Google the framework is always


up to date.

Also it always incorporates the latest development trends in the


market.

DEPARTMRNT OF MCA 4
Features of Angular JS
1. MVC (Model View Controller) -

This is a design pattern used in all modern day web applications.

 This pattern is based on splitting the business logic layer, data layer,
and presentation layer into separate sections.

 The division into different sections is done so that each one could
be managed more easily.

DEPARTMRNT OF MCA 5
Features of Angular JS…

2. Data model binding -


No need to write special code to bind data to the HTML controls.
This can be done by Angular by just adding a few snippets of code.
3. Writing less code -
When carrying out DOM manipulation a lot of JavaScript was required
to be written to design any application.
But with angular, you will be amazed with the lesser amount of code
need to write for DOM manipulation.

DEPARTMRNT OF MCA 6
Features of Angular JS…

4. Speed and Performance -


 New component router loads angular app quickly.

 It provides the ability of automatic code splitting too.

 Therefore only that code is loaded which is requested to render


the view.

DEPARTMRNT OF MCA 7
Features of Angular JS…

5. Productivity -
Template in the angular application allows a developer to create user
interface quickly.
Angular command line interface (CLI) helps to build an application
very fast.
Intelligent code completion is possible through IDE.
It provides instant errors and provides other feedbacks also.

DEPARTMRNT OF MCA 8
Advantages of AngularJS

1. Easy to learn:
AngularJS is simple to learn for those who are familiar with
HTML, JavaScript, and CSS. Learning AngularJS expands
developers’ chances in the Web Development sector.
2. Declarative UI:
A declarative user interface enhances understanding and
management. HTML enables developers and designers to work
together. Designers can begin to build the user interface, while
developers use declarative binding language skills to connect
the various UI components to data models
3. Single Page Application
Single Page Applications are supported by AngularJS. Single
page application means only a single HTML web page is
loaded and further updation is done on that single page only.
Since it is mostly used to create single page application and
single page application works fast as well as it is user-friendly.
4. Open Source
AngularJs is an open source JavaScript MVC framework,
therefore, at affordable costs custom application can be
available to anyone. Since it is an open source, therefore, It
provides the advantage of easily changing the source code to
provide clarification.
5. No pre-requisite knowledge
HTML, CSS and JavaScript are to work on AngularJS. So, there
is no need to learn any other scripting language. So if you want to
learn angular, it is a plus point for you as HTML, CSS and
javascript are simple easy to learn and if you are familiar with this
languages then its quite easy task for you to learn angular.

6. Easy to test
Angular is JavaScript framework and JavaScript is dynamically
typed language. But there is no help of compiler in angular.
Therefore, it is necessary to write strong test code for it. As there
is an in built comes in it, which makes it easier to test individual
components of the code. Both unit testing and integration testing
is supported by angular.
Disadvantages of AngularJS

1. Less secure
There is no server authorization and authentication in angular.
Authorization means granting permission for data access and
identifying a user by validating credentials. AngularJs can’t
provide both the features, that’s we call it less secure.
2. Complexity
Despite being an outstanding tool for web development, still
AngularJS is a complex framework. Even some experienced web
developers find it confusing using this framework. For reading the
code, you must understand the frontend development. However,
there are many experts who have specialized with this and knows
every little details about it. So you can look for their help.
3. Memory leakage
Also, it is a framework of JavaScript and there is an issue of
memory leak in JavaScript. Memory leak leads to various other
issues too such as slowdowns, crashes, and high latency.
4. No specific way
It is very vast and complex. In angular, there are many ways to
perform the same task so it is difficult to predict which is the most
optimized way to perform a certain task.

5. Not supported everywhere


Internet Explorer 8.0 doesn’t support AngularJs.
Applications that are built using angular technology are
Malhar-Angular-Dashboard, Viktor
NV-1 (open-source musical instrument)
Taiga (Project Manager application for agile developers and
designers)
Proton Mail (Encrypted Webmail Interface)
Sound Node (Sound Cloud for desktop )
Introduction
▪ There are many integrated development environments we can use
for Angular JS development.
▪ Some of the popular ones are:
1. WebStorm
2. Sublime Text
3. AngularJS Eclipse
4. Visual Studio
▪ In our example we are using WebStorm as our IDE.
DEPARTMENT OF MCA 3
Hello world, Angular JS.
<!DOCTYPE html>
<html ng-app="app">
<head>
<meta charset="UTF-8">
<title>Guru99</title>
</head>
<body>

DEPARTMENT OF MCA 4
<h1 ng-controller="HelloWorldCtrl">{{message}}</h1>
<script src="[Link]
<script type=”text/javascript”>
[Link]("app", []).controller("HelloWorldCtrl",
function($scope) {
$[Link]="Hello World" } )
</script>
</body>
</html>

DEPARTMENT OF MCA 5
Code Explanation
1. The “ng-app” keyword is used to denote that this application should
be considered as angular JS application.
2. The controller is what is used to hold the business logic. In the h1
tag, we want to access the controller, which will have the logic to
display “Hello World”, so we can say in this tag we want to access
the controller named “HelloWorldCtrl”.

DEPARTMENT OF MCA 6
Cont.…
3. We are using a member variable called “message” which is nothing
but a placeholder to display the “Hello World” message.
4. The “script tag” is used to reference the angular JS script which has
all the necessary functionality for angular JS. Without this reference,
if we try to use any Angular JS functions, they will not work.
5. “Controller” is the place where we are actually creating our business
logic, which is our controller. What is important to note that we are
defining a controller method called ‘HelloWorldCtrl’.

DEPARTMENT OF MCA 7
Cont.…
6. We are creating a “function” which will be called when our code call
this controller. The $scope object is a special object in Angular JS
which is a global object used within Angular JS. The $scope object
is used to manage the data between the controller and the view.
7. We are creating a member variable called “message”, assigning it
the value of “HelloWorld” and attaching the member variable to the
scope object.

DEPARTMENT OF MCA 8
OUTPUT

DEPARTMENT OF MCA 9
3
What is AngularJS MVC?

▪ Software design pattern for designing and developing a web


application.
▪ AngularJS MVC divides an application in to three parts
Model part, View part, Controller part.

Department Of MCA
4

MVC Architecture:

•Responsible for maintaining


Model data

•Responsible for displaying all or


View a portion of the data to the user

•Controls the interaction


Controller between the Model and view

Department Of MCA
5
How MVC Works in AngularJS?

User

View Controller

Model

Department Of MCA
6
Cont….
1. MVC can be implemented in AngularJS through the usage of
JavaScript and HTML.
2. The model part can be implemented by HTML, where as the model
and the controller part can be implemented by JavaScript.
3. The controller receives all request for the application and then
works with the model to prepare any data needed by the view.
4. The view then uses the data prepared by the controller to generate a
final presentable response.

Department Of MCA
7

Example:

Controller

Request
User Enter URL
Browser
Response

View Model

Department Of MCA
What are Directives?
● Directives are markers on DOM elements that tell AngularJS to
attach specific behaviors to that element.
● They allow you to extend HTML with new attributes and tags.
● Angular comes with several built-in directives like ng-model,
ng-repeat, ng-if, etc.
● You can also create custom directives to add any custom behavior
to elements.
Why Use Directives?
● Cleaner and more maintainable code by encapsulating
complex logic into reusable directives.
● Separation of concerns - keep HTML for structure and
directives for behavior.
● Easier to build component-based architecture.
Type of Directives
● Element directives -directives that turn an element into a widget.
Ex. <my-directive></my-directive>
● Attribute directives - add behavior to an existing element. Ex.
<div my-directive="exp"></div>
● Class directives - add/remove CSS classes. Ex.
<div class="my-directive: exp;"></div>
● Comment directives - manipulate the DOM. Ex.
<!-- directive: my-directive exp -->
Built-in directives
ng-app - Defines the root element of an AngularJS application.
ng-init - Initializes application data on a page.
ng-model - Binds form elements like input, select, textarea to
application data.
ng-repeat - Repeats html for each item in a collection.
ng-if - Conditionally includes or removes html based on
expression.
ng-src - Sets image source dynamically.
ng-class - Applies CSS classes conditionally.
ng-click - Attach a click handler to an element.
ng-switch - Conditionally swaps DOM elements.
ng-include - Includes external HTML fragment.
ng-submit - Attach handler to form submit event.
ng-options - Populates dropdown from array or object.
ng-bind - Sets text content to application data.
Example

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


<p>Name:
<input type="text" ng-model="firstName"></p>
<p>You wrote: {{ firstName }}</p>
</div>
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.
Why do we need angular js directives.

❖AngularJS directives are like special instructions that you can give to
HTML elements. They allow you to extend HTML with new behaviors,
create reusable components, and add interactivity to your web application.

❖Think of a directive as a small code snippet that you can attach to an


element (like a <div> or a custom element) or an attribute (like ng-click or
ng-model) in your HTML code. This code snippet tells AngularJS what to
do with that element or attribute.

ALPINE SKI HOUSE


ng-model
❖Ng-model is a directive that represent models and its primary purpose is to
bind the “view” to the model.
❖Ng-model directive will ensure that the data in the “view” and that of your
“model” are kept in sync that whole time.
❖The ng-model attributes is used for binding controls such as input, text area
and selects in the view into the model.
❖The ng-model attribute maintains the state of the control (By state, we mean
that the controls and the data is bound to be always kept in sync. If the value
of data changes, it will automatically change the value in the control and
vice versa.

ALPINE SKI HOUSE


ng-model code example
<html>
<head>
<title>Event Registration</title>
</head>
<body>
<script src=“[Link]
<h1>Guru99 Global Event</h1>
<div ng-app=“ “ ng-init=“quantity=1;price=5”>
People : <input type=“number” ng-model=“quantity”>
Registration Price :<input typr=“number” ng-model=“price”>
Total :{{quantity*price}}
</div>
</body> </html>
ALPINE SKI HOUSE
ng-model code example output
Guru99 Global Event

People : 1

Registration Price : 5

Total : 5

ALPINE SKI HOUSE


ng-repeat
❖Angular provide a directive called “ng-repeat” which can be used to display
repeating values defined in our controller.
❖ng-repeat is a built-in AngularJS directive used to iterate over collections
(arrays or objects) and create HTML elements dynamically for each item in
the collection.
❖The basic syntax of ng-repeat is ng-repeat="item in collection", where item
is a local variable representing the current item in the iteration, and
collection is the array or object to loop through.
❖When using ng-repeat with arrays, each element of the array will be
accessible through the item variable inside the loop.
❖Inside the ng-repeat block, you can use curly braces {{ expression }} to
display the properties of each item. For example, {{ [Link] }} will
display the name property of each item.
ALPINE SKI HOUSE
ng-repeat code example
<html>
<head>
<title>Event Registration</title>
</head>
<body>
<script src=“[Link]
<h1>Guru99 Global Event</h1>
<div ng-app=“ “ ng-init=“chapters=[‘Controllers’,’Models’,’Filters’]”>
<ul>
<li ng-repeat=“name in chapters”> {{names}}</li>
</ul>
</div>
</body> </html>
ALPINE SKI HOUSE
ng-repeat code example output

Guru99 Global Event


• Controllers
• Models
• Filters

ALPINE SKI HOUSE


Custom directives
▪ A custom directives in Angular JS is a user-defined directives
with your desired functionality.
▪ Even though Angular JS has a lot of powerful directives out of
the box, sometime custom directives are required.

How to create custom directives?


• The custom directives in our case is simply going to inject a div
tag which has the text “AngularJS Tutorial” in our page when the
directives called.

Department of MCA 3
Contd..

<!DOCTYPE HTML>
<html>
<head><meta charset=“UTF 8”>
<title>Event Registration</title>
</head>
<body>
<script src=[Link] </script>
<script src=[Link] </script>
<script src=[Link]
<script src=[Link] </script>
Department of MCA 4
<h1>Guru99 Global Event</h1>
<div ng-app=“Demoapp”>
<div ng-guru=“”></div>
</div>
<script type=“text/javascript”>
Var app=[Link](‘DemoApp’,[]);
[Link](‘ngGuru’,function() {
return {
template: ‘<div>Angular JS Tutorial</div>’
}
});
</script>
</body>
</html> Department of MCA 5
Code Explanation

1. We are first creating a module for our angular application. This is


required to create a custom directive because the directive will be
created using this module .

2. We are now creating a custom directive called “ngGuru” and defining


a function which will have custom code for our directive.

Department of MCA 6
Note:-

▪ Note that when defining the directive, we have defined it as ngGuru with
the letter ‘G’ as capital.
▪ And when we access it from our div tag as a directive we are accessing it
as ng-guru. This is how angular understands custom directives defined in
an application.
▪ Firstly the name of the custom directive should start with the letters ‘ng’.
▪ Secondly the hyphen symbol ‘-‘ should only be mentioned when calling
the directive.
▪ And thirdly the first letter following the letters ‘ng’ when defining the
directive can be either lower or uppercase.

Department of MCA 7
3. We are using the template parameter which a parameter defined by
Angular for custom directives. In this, we are defining that whenever this
directive is used, then just use the value of the template and inject it in the
calling code.

4. Here we are now making use of our custom created “ng-guru” directive.
When we do this, the value we defined for our template “<div>Angular JS
Tutorial</div>” will now be injected here.

If the code is executed successfully, the following Output will be shown when
you run your code in the browser.

Department of MCA 8
Output:

Department of MCA 9
Directives
❖AngularJS directives are extended HTML attributes having the
prefix ng-.
❖Directives are markers on the DOM element which tell Angular JS
to attach a specified behavior to that DOM element or even transform
the DOM element with its children.
❖During compilation, the HTML compiler traverses the DOM
matching directives against the DOM elements.

DEPARTMENT OF MCA 3
DEPARTMENT OF MCA 4
The scope is a JavaScript object
Which Basically Blinds the
What is $Scope in “controller” and the “view”.
Angular JS?

One can define member variables


in the scope within the controller
which can then be accessed by the
view

DEPARTMENT OF MCA 5
Example

DEPARTMENT OF MCA 6
Setting up or adding behaviour

▪In order to react to events or execute some sort of


computation/processing in the View, we must provide behavior to the
scope.
▪ Behaviors are added to scope objects to respond to specific events
that may be triggered by the View.
▪Once the behavior is defined in the controller, it can be accessed by
the view.

DEPARTMENT OF MCA 7
var mymodule=[Link](“asm", []);
[Link]("mycontroller", function($scope){
$[Link] = “Aneesh Shetty";
$[Link] “Mangalore";
$[Link] = function(){
return "this is function variable: ”+ $[Link] +
$[Link];
};
});
DEPARTMENT OF MCA 8
 Angular gives the facility to access the
controller’s member variable directly from
custom directives without the need of the
scope object.
 This becomes necessary at times because in
an application you may have multiple scope
objects belonging to multiple controllers.
 So there is a high chance that you could
make the mistake of accessing the scope
object of wrong controller.

2
DEPARTMENT OF MCA
 In such scenario’s there is a way to specifically
mention saying “I want to access this specific
controller” from my directive.

EXAMPLE:

3
DEPARTMENT OF MCA
<!DOCTYPE html>
<html>
<head>
<meta chrset="UTF 8">
<title>Event Registration</title>
</head>
<body>
<script src="[Link]
[Link]"></script> <script
src="[Link]
<script src="[Link]
</script>
<script src="[Link]

4
DEPARTMENT OF MCA
<h1> Guru99 Global Event</h1>
<div ng-app="DemoApp" ng-controller="DemoController">
<div ng-guru99=""></div>
</div> <script type="text/javascript">
var app = [Link]('DemoApp',[]);

[Link]('DemoController',function() {
[Link] = "Angular"; });
[Link]('ngGuru99',function(){
return {
controller: 'DemoController',
controllerAs: 'ctrl',
template: '{{[Link]}}'
};
});
</script>
</body>
</html>

5
DEPARTMENT OF MCA
Code Explanation:

 We first create a controller called,


“DemoController”. In this we will define a
variable called “tutorialName” and this time
instead of attaching it to the scope object, we will
attach it directly to the controller.
 In our custom directive, we are specifically
mentioning that we want to use the controller
“DemoController” by using the controller
parameter keyword.

6
DEPARTMENT OF MCA
 We create a reference to the controller
using the “controllerAs” parameter. This is
defined by Angular and is the way to
reference the controller as a reference.
 Note: –It is possible to access multiple
controllers in a directive by specifying
respective blocks of the controller,
controllerAs and template statements.
 Finally, in our template, we are using the
reference created in step 3 and using the
member variable that was attached directly
to the controller in Step 1.
 If the code is executed successfully, the
following Output will be shown when you
run your code in the browser.
7
DEPARTMENT OF MCA
OUTPUT:

8
DEPARTMENT OF MCA
INTRODUCTION

1. Directives in angular js can be used to create reusable components.

2. We have already saw the power of custom directives, but we can


take that to next level by building our own re-usable directives.

3. For example-that we need to inject code that would always show the
below HTML tags across multiple screens, which is basically just an
input for the “Name” and “age” of the user.

DEPARTMENT OF MCA 3
Cont.…..
4. To reuse this function on multiple screens without coding each time,
we create a master control or directive in angular to hold these
controls(“Name” and “age” of the user).

5. A master control is a centralized component or service that holds


reusable function

6. Instead of entering the same code for the below screen every time, we
can actually embed this code in a directive and embed that directive at
any point in time.

DEPARTMENT OF MCA 4
EXAMPLE
<!DOCTYPE html>
<html>
<head>
<meta chrset="UTF 8">
<title>Event Registration</title>
</head>
<body>
<script src="[Link]
<script src="[Link]

DEPARTMENT OF MCA 5
Contd..
<script src="[Link]
<script src="[Link]
<h1> Guru99 Global Event</h1>
<div ng-app="DemoApp">
<div ng-guru=""></div>
</div>
<script type="text/javascript">
var app = [Link]('DemoApp',[]);
[Link]('ngGuru',function(){
return {
DEPARTMENT OF MCA 6
Contd…

template: '&nbsp;&nbsp;Name <input


type="text"><br><br>&nbsp;&nbsp;&nbsp;Age<input type="text">'
};
});
</script>
</body>
</html>

DEPARTMENT OF MCA 7
Contd…

❑ In the code snippet for a custom directive, what changes is just the value
which is given to the template parameter of our custom directive.

❑Instead of a plan five tag or text, we are actually entering the entire
fragment of 2 input controls for the “Name” and “age” which needs to be
shown on our page

DEPARTMENT OF MCA 8
OUTPUT

DEPARTMENT OF MCA 9
HANDLING EVENTS IN A DIRECTIVE

• Events such mouse clicks or button clicks can be handled from within
directives itself.
• This is done using the link function.
• The link function is what allows the directive to attach itself to the
DOM elements in an HTML page.
• Syntax:
link: function($scope, element, attrs)
• The link function normally accepts 3 parameters including scope, the
element that the directive is assosciated with, and the attributes of the
target element.

DEPARTMENT OF MCA 3
CONTD…

DEPARTMENT OF MCA 4
CONTD…
Example
<DOCTYPE html>
<html>
<head>
<mets chrset=“UTF 8”>
<title>Event Registratio</title>
</head>
<body>
<script src=[Link]
</script>

DEPARTMENT OF MCA 5
CONTD…
<script src=[Link]
</script>
<script src=[Link]
</script>
<script src=[Link]
</script>

<h1> Guru99 Global Event</h1>


<div ng-app=“DemoApp”>
<div> ng-guru=“”>Click Me</div>
DEPARTMENT OF MCA 6
CONTD…

</div>

<Script type=“text/javascript”>
var app=[Link](‘DemoApp’,[]);
[Link](‘ngGuru’,function(){
return{
link:function($scope,element,attrs) {
[Link](‘click’,function() {

DEPARTMENT OF MCA 7
CONTD…

[Link] ( ‘You clicked me ’ );


});}
}});
</script>
</body>
</html>

DEPARTMENT OF MCA 8
CODE EXPLANATION
• We are using the link function as defined in angular to give the ability
of the directives to access events in the HTML DOM.
• We are using the ‘element’ keyword because we want to respond to an
event for an HTML DOM element, which is in our case will be the
“div” element.
• We are then using the “bind” function and saying that we want to add
custom functionality to the click event of the element.
• The ‘click’ word is the keyword, which is used to denote the click
event of any HTML control.
• For example, the HTML button control has the click event.

DEPARTMENT OF MCA 9
CONTD…

• In our example,we want to add a custom code to the click event of our
“div” tag, we use the ’click’ keyword.
• Here we are saying that we want to substitute the inner HTML of the
element(div element) with the text ‘You Clicked Me!’.
• We are defining our div tag to use the ng-guru custom directive.
• Initially the text ‘Click Me’ will be shown to the user because this is
what has been initially defined in the div tag. When you actually click
on the div tag, ‘You Clicked Me!’ this text will be displayed.

DEPARTMENT OF MCA 10
CONTD…

• OUTPUT

DEPARTMENT OF MCA 11
 Expression are variables which were defined in the double
braces {{ }}.

 Commonly used in Angular JS.

3
Department of MCA
 {{ expression }}

 A simple example of an expression is {{5+6}}

Department of MCA 4
 Angular .JS expressions are used to bind data to HTML.

 the same way as the ng-bind directive.

 Angular JS displays the data exactly at the place where the


expression is placed.

Department of MCA 5
<!DOCTYPE html>
<html>
<head> <meta chrset="UTF 8">
<title>Event Registration</title>
</head>
<body>
<script src="[Link]
<script src="[Link]
<h1> Guru99 Global Event</h1>
<div ng-app=""> Addition : {{6+9}} </div>
</body>
</html>

6
Department of MCA
From the output,
It can be seen that the addition of the two numbers 9 and 6 take place and the added value of 15 is
displayed.

7
Department of MCA
Department of MCA 8
Code Explanation:

 The ng-app directive in our example is blank as shown in


above . This only means that there is no module to assign
controllers, directives, services attached to the code.

 We are adding a simple expression which looks at the addition


of 2 numbers.

 If the code is executed successfully, the following Output will


be shown as above .

9
Department of MCA
EXPRESSION
 Expression are variables which were defined in
the double braces{{ }}
 It can contain literals, operators, and variables.
 Syntax:{{expression}}
 Example:
<span>
1+2={{1+2}}
</span>
OUTPUT:
1+2=3 3

Department of MCA
EXPRESSION CAPABILITIES
 Angular expressions are like JavaScript
expressions. Hence ,it has the same power and
flexibility.
 The modular architecture enhances flexibility
and functionality ,without compromising
stability.

 In
JavaScript ,when you try to evaluate
undefined properties ,it generates a
ReferenceError or TypeError. 4

Department of MCA
 In Angular ,expression evaluation is forgiving
and generate an undefined or null.
 Example:
In JavaScript, evaluating a.b.c throws an
exception if a is not defined.
{{a.b.c}}

 One can use filters within expressions to format


data before displaying it.
 Example:
<p>
The name is {{ lastName | uppercase }}
</p> 5
EXPRESSION LIMITATIONS
 Thereis currently no availability to use
conditionals, loops, or exceptions in an Angular
expression.
e.g. if-else, ternary, for loop, while loop etc.

The reason behind this is core to the


AngularJS philosophy that application logic
should be in controllers, not the views.
If you need a real conditional, loop, or to
throw from a view expression, delegate to a
JavaScript method instead. 6

Department of MCA
 You cannot declare functions in an Angular
expression ,even inside ng-init directive.
 This is to avoid complex model transformation
logic inside templates.
 One cannot create regular expressions in an
Angular expression .
 A regular expression is a combination of
symbols and characters ,which are used to find
for strings such as .*.txt$.
 One cannot use comma or void in an Angular
expression

Department of MCA
Content
What is Controller in AngularJS?
What Controller does from Angular’s Perspective?

DEPARTMENT OF MCA
What is Controller in AngularJS?
A Controller in AngularJS takes the data from the View,
processes the data, and then sends that data across to the
view which is displayed to the end user.
The Controller will have your core business logic. The
controller will use the data model, carry out the required
processing and then pass the output to the view which in turn
is displayed to the end user.

DEPARTMENT OF MCA
What Controller does from Angular’s Perspective?
 The controller’s primary responsibility is to control the data
which gets passed to the view.
 The scope and the view have two-way communication.
 The properties of the view can call “functions” on the scope.
Moreover events on the view can call “methods” on the scope.
 The below code snippet gives a simple example of a function.
◦ The function($scope) which is defined when defining the
controller and an internal function which is used to return the
concatenation of the $[Link] and $[Link].
◦ In AngularJS, when you define a function as a variable, it is
known as a Method.

DEPARTMENT OF MCA
Examlpe

DEPARTMENT OF MCA
 Data in this way pass from the controller to the scope, and then
the data passes back and forth from the scope to the view.

 The scope is used to expose the model to the view.

 The model can be modified via methods defined in the scope


which could be triggered via events from the view.

 We can define two way model binding from the scope to the
model.

DEPARTMENT OF MCA
 Controllers should not ideally be used for manipulating the
DOM.
 Best practice is to have controller’s based on functionality.

֍ For example, if you have a form for input and you need a
controller for that, create a controller called “form controller”.

DEPARTMENT OF MCA
How to Build a Basic Controller in
AngularJS
Below are the steps to create a controller in AngularJS:
Step 1) Create a basic HTML Page
 Before we start with the creation of a controller, we need to first
have our basic HTML page setup in place.
 The below code snippet is a simple HTML page which has a title of
“Event Registration” and has references to important libraries such as
Bootstrap, jquery and Angular.

DEPARTMENT OF MCA 2
DEPARTMENT OF MCA 3
Conti…
1. We are adding references to the bootstrap CSS stylesheets, which
will be used in conjunction with the bootstrap libraries.
2. We are adding references to the angularjs libraries. So now
whatever we do with [Link] going forward will be referenced
from this library.
3. We are adding references to the bootstrap library to make our web
page more responsive for certain controls.
4. We have added references to jquery libraries which will be used for
DOM manipulation. This is required by Angular because some of
the functionality in Angular is dependent on this library.
DEPARTMENT OF MCA 4
Step 2) Check the files and file structure

DEPARTMENT OF MCA 5
Conti…
1. First we segregate our files into 2 folders as is done with any conventional
web application. We have the “CSS” folder. It will contain all our
cascading style sheet files, and then we will have our “lib” folder which
will have all our JavaScript files.
2. The [Link] file is placed in the CSS folder and it used for adding a
good look and feel for our website.
3. The [Link] is our main file which was downloaded from the angularJS
site and kept in our lib folder.
4. The [Link] file will contain our code for the controllers.

DEPARTMENT OF MCA 6
Conti…
5. The [Link] file is used to supplement the [Link] file to
add bootstrap functionality to our web application.
6. The jquery file will be used to add DOM manipulation
functionality to our site.

DEPARTMENT OF MCA 7
Step 3) Use AngularJS code to display the output
What we want to do here is just to display the words “AngularJS” in
both text format and in a text box when the page is viewed in the
browser.

DEPARTMENT OF MCA 8
Example:

DEPARTMENT OF MCA 9
Code Explanation:
• The ng-app keyword is used to denote that this application should be
considered as an angular application. Anything that starts with the prefix ‘ng’ is
known as a directive. “DemoApp” is the name given to our [Link]
application.
• We have created a div tag and in this tag we have added an ng-controller
directive along with the name of our Controller “DemoController”. This basically
makes our div tag the ability to access the contents of the Demo Controller. You
need to mention the name of the controller under the directive to ensure that
you are able to access the functionality defined within the controller.
• We are creating a model binding using the ng-model directive. What this does is
that it binds the text box for Tutorial Name to be bound to the member variable
“tutorialName”.
DEPARTMENT OF MCA 10
Conti…
• We are creating a member variable called “tutorialName” which
will be used to display the information which the user types in
the text box for Tutorial Name.
• We are creating a module which will attach to our DemoApp
application. So this module now becomes part of our application.
• In the module, we define a function which assigns a default
value of “AngularJS” to our tutorialName variable.

DEPARTMENT OF MCA 11
OUTPUT

o Since we assigned the variable tutorial Name a value of “Angular JS”,


this gets displayed in the text box and in the plain text line.

DEPARTMENT OF MCA 12
Content
• What is Controller?
• How to define Methods in controller

DEPARTMENT OF MCA
What is Controller?
• A Controller in AngularJS used to control the flow of data of
Angular JS application.
• The Controller are responsible for handling user input, manipulating
data and updating view.
• The Controller helps to separate the concerns of an application by
allowing you to keep the business logic separate from the
presentation logic.

DEPARTMENT OF MCA
How to define Methods in controller
• The ng-controller directive defines the application controller.
• A controller is a JavaScript object, created by JavaScript object
constructor.
• Here a controller can also have methods (variables as function)
• $scope is defined when the controller is defining and it returns the
concatenation of the $[Link] and $[Link].

DEPARTMENT OF MCA
Syntax
<element ng-controller="expression">
Contents...
</element>

DEPARTMENT OF MCA
Example Program

DEPARTMENT OF MCA
Contents

 What are Built-in Filters!

 Using Built-in filter - Uppercase!

 Using Built-in filter -Numbers!


Built-in Filters

 In AngularJS, filters are used to format and


manipulate data before displaying it in the UI.
 They are applied using the double curly braces
syntax {{ expression | filter }}.
 There are several built-in filters available in
AngularJS that allow you to perform various
transformations on data.
 Example: 'currency', 'date', 'orderby', 'number',
'uppercase' etc
Built-in filters- Uppercase

a. In AngularJS, the "uppercase" built-in filter is used


to transform a given text to uppercase.
b. It's commonly used in templates to change the
appearance of text by making it all uppercase.
c. For example, if you have a variable text containin
g "Hello World," you can apply the filter like this: {{
text | uppercase }}, and the output will be "HELLO
WORLD".
Cont....

<body>
<div ng-controller="myController">
<p>Original Text: {{ text }}</p>
<p>Uppercase Text: {{ text | uppercase }}</p>
</div>
<script>
var app = [Link]('myApp', []);
[Link]('myController', function($scope) {
$[Link] = 'Hello, AngularJS!';
});
</script>
</body>
</html>
Cont....

.
Built-in filters - Numbers

• In AngularJS, you can use built-in filters to format and


manipulate numbers in your application's templates.
• Filters are used to transform data before displaying it to
users.
• Here's an explanation of how to use built-in number filters:

 currency: This filter formats a number as a currency string.

{{ price | currency }}

 number: This filter formats a number as text. You can


specify the number of decimal places you want to display

{{ value | number:2 }}
Cont ....
 percentage: This filter formats a number as a
percentage:
{{ percentageValue | percentage }}

 json: This filter formats an object as a JSON


string. While not a number-specific filter, it can
be used with objects that contain numbers:
{{ myObject | json }}
Cont....

<body ng-controller="NumberController">
<h2>Number Filters Example</h2>
<p>Original Number: {{ number }}</p>
<p>Rounded to 2 decimal places: {{ number | number:
2 }}</p>
<p>Currency Format: {{ number | currency }}</p>
<p>Percentage Format: {{ number | percentage }}</p>
</body>
</html>
Cont..

//js code

$[Link] = 1234.5678;
CONTENT:
 Introduction

 Types of filter
 currency
 json

Department of MCA
INTRODUCTION :
What is AngularJs Filter?

 AngularJS filter is a tool,which we can use to


format the data.

 With this filter, the user can see and modify


according to the requirement.

 Itis added in angular to format the data is being


displayed on the view part. 3

Department of MCA
CURRENCY :
 This filter formats a currency filter to a number.

 Suppose,ifwe wanted to display a number with


a currency such as $, then this filter can be used.

 In
the example we will use a controller to send a
number to a view via the scope object.

 We will then use a filter in the view to apply the


currency filter. 4

Department of MCA
EXAMPLE :
<!DOCTYPE html>
<html>
<head>
<meta charset=“UTF 8”>
<title>Event Registration</title>
</head>
<body>
<script src=“[Link]
[Link]”>
</script>
<script
src=[Link]
</script>
<script src=“[Link]
</script> 5

Department of MCA
CONT…
<h1> Guru99 Global Event</h1>
<div ng-app=“DemoApp” ng-
controller=“DemoController”>
This tutorial Price is {{tutorialprice | currency}}
</div>
<script type=“text/javascript”>
var app=[Link](‘DemoApp’,[]);
[Link](‘demoController’,function($scope) {
$[Link]=20.56;
}};
</script>
</body>
6
<html>
Department of MCA
CODE EXPLANATION:
 Here we are passing a number in a member
variable called tutorialprice and attaching it to
the scope object.
 We are using the member variable tutorialprice
and putting a filter symbol(|) along with the
currency filter.
Note :
 The currency which is applied depends on the
language settings which are applied to the
machine.
7

Department of MCA
OUTPUT :

Department of MCA
JSON :
 Thisfilter formats a JSON like input and applies
the JSON filter to give the output in JSON.

Department of MCA
PROGRAM :
<!DOCTYPE html>
<html>
<head>
<meta chrset=“UTF 8”>
<title>Event Registration</title>
</head>
<body>
<script
src=“[Link]
[Link]”>
10
</script>
Department of MCA
CONT…
<script
src=“[Link]
.js”>
</script>
<script src=“[Link]
[Link]”>
</script>
<h1> Guru99 Global Event</h1>
<div ng-app=“DemoApp” ng-
controller=“DemoController”>

This tutorial is {{tutorial | json}}


11
</div>
Department of MCA
CONT…
<script type=“text/javascript”>
var app=[Link](‘DemoApp’,[]);
[Link](‘DemoController’,function($scop
e){

$[Link]={TutorialID:12,
tutorialname:”Angular”};
});
</script>
</body>
</html> 12

Department of MCA
CODE EXPLANATION:
 Here we passing a number in a member variable
called “tutorial” and attaching it to the scope
object.

 Thismember variable contains a JSON type


string of Tutorial ID:12, and
TutorialName:”Angular”.

 We are using the member variable tutorial and


putting a filter symbol (|) along with the JSON
filter.
13

Department of MCA
OUTPUT:

14

Department of MCA
• A Filter in AngularJS helps to format the value of an expression to display to the
user without changing the original format.

• For example, if you want your string in either lowercase or uppercase, you can do
it using filters.

• There are built-in filters such as ‘lowercase’, ‘uppercase’, which can retrieve the
lowercase and uppercase output accordingly.
• Sometimes the built-in filters in Angular cannot meet the needs or requirements
for filtering output. In such a case, an AngularJS custom filter can be created,
which can pass the output in the required manner.
• In the custom filter AngularJS example, we are going to pass a string to the view
from the controller via the scope object, but we don’t want the string to be
displayed as it is.

• We want to ensure that whenever we display the string, we will pass a custom
filter in AngularJS, which will append another string and display the completed
string to the user.
<div ng-app = "DemoApp" ng-controller = "DemoController">
This tutorial is {{tutorial | Demofilter}}
</div>
<script type = "text/javascript">
var app = [Link]('DemoApp',[]);
[Link]('Demofilter',function() {

return function(input)
{
return input + " Tutorial";
}
});
[Link]('DemoController',function($scope) {
$[Link] = "Angular";
});
1. Here we are passing a string in a member variable called tutorial and
attaching it to the scope object.

2. Angular provides the filter service which can be used to create our custom filter.
The ‘Demofilter’ is a name given to our filter.

3. This is the standard way in which custom filters in AngularJS are defined wherein a
function is returned. This function is what contains the custom code to create the
custom filter. In our function, we are taking a string which is passed
from our view to the filter and appending the string to this.

4. We are using our Demofilter on our member variable which was passed from the
controller to the view.
If the code is executed successfully, the following Output will be shown when you run
your code in the browser.

Output:

From the output,


• It can be seen that our custom filter has been applied and
• The word ‘Tutorial’ has been appended at the end of the string, which was passed in
member variable tutorial.
Content
 $http service
 $timeout service
 $interval service

2 Department of MCA
The $http Service
 The $http service is one of the most common used
services in AngularJS applications. The service makes a
request to the server, and lets your application handle the
response.
 Example :
<!DOCTYPE html>
<html>
<script
src="[Link]
9/[Link]"></script>
<body><div ng-app="myApp" ng-controller="myCtrl">
3 Department of MCA
The $http Service…
<h1>{{myWelcome}}</h1>
</div>
<p>The $http service requests a page on the server</p>
<script>
var app = [Link]('myApp', []);
[Link]('myCtrl', function($scope, $http) {
$[Link]("[Link]").then(function (response) {
$[Link] = [Link];
});});
</script>
</body></html>
4 Department of MCA
The $http Service…

5 Department of MCA
The $timeout Service
<p>The $timeout service runs a function after a
specified number of milliseconds.</p>
<script>
var app = [Link]('myApp', []);
[Link]('myCtrl', function($scope, $timeout) {
$[Link] = "Hello World!";
$timeout(function () {
$[Link] = "How are you today?";
}, 2000);});
</script></body></html>
6 Department of MCA
The $timeout Service …

7 Department of MCA
The $interval service
 <p>The $interval service runs a function every
specified milisecond.</p><script>
var app = [Link]('myApp', []);
[Link]('myCtrl', function($scope, $interval) {
$[Link] = new
Date().toLocaleTimeString();
$interval(function () {
$[Link]=newDate().toLocaleTimeString();
}, 1000);});</script>

8 Department of MCA
The $interval service…

9 Department of MCA
CONTENTS

Introduction events in angular JS


NG click
An Events in Angular JS can be used
to perform particular tasks, based on the
action taken.
 Both Angular Event & the HTML
Event will be executed & will not
overwrite with an HTML Event. It can be
added using the Directives mentioned
below:
ng-mousemove: The movement of the mouse
leads to the execution of the event.
ng-mouseup: Movement of the mouse upwards
leads to the execution of the event.
ng-mousedown: Movement of the mouse
downwards leads to the execution of the event.
ng-mouseenter: Click of the mouse button
leads to the execution of the event.
ng-mouseover: Hovering the mouse leads to
the execution of the event.
ng-cut: Cut operation leads to the execution of
the event.
ng-copy: Copy operation leads to the
execution of the event.
ng-keypress: Press of key leads to the
execution of the event.
ng-keyup: Press of upward arrow key leads
to the execution of the event.
ng-keydown: Press of downward arrow
key leads to the execution of the event
ng-click: Single click leads to the execution
of the event
ng-dblclick: Double click leads to the
execution of the event.
ng-blur: Fired when an HTML element loses its
focus.
ng-change:It is used whenever the value of an input
element changes.
ng-focus: It is used to apply custom behavior when an
element is focused.
ng-paste: It is used to specify custom behavior
functions when the text in input fields is pasted into an
HTML element.
ng-mouseleave: It is used to apply custom behavior
when a mouse-leave event occurs on a specific HTML
element
NG CLICK DIRECTIVE

The ng-click directive tells Angular JS


what to do when an HTML element is
clicked..
 It can be used to show/hide some
element or it can pop up an alert when
the button is clicked.
 Parameter Value expression: It
specifies when the particular element is
clicked then the specific expression will
be evaluated.
Expression: An expression to
execute when an element is clicked.

Syntax: <element ng-


click="expression"></element>

Example:-
<!DOCTYPE html>
<html>
<script
src="[Link]
[Link]"></script>
<body ng-app="myApp">

<div ng-controller="myCtrl">
<p>Click the button to run a function:</p>
<button ng-click="myFunc()">OK</button>
<p>The button has been clicked {{count}} times.</p>
</div>

<script>
[Link]('myApp', [])
.controller('myCtrl', ['$scope', function($scope) {
$[Link] = 0;
$[Link] = function() {
$[Link]++;
};
}]);
Cont…

</script>
</body>
</html>

OUTPUT

You might also like