Sei sulla pagina 1di 182

_A..

...A.

. ~
N ••
B: ·1<·T S
•••••H•·{.//\;
1
./;'•: ,.· .·. . ~

N Benchmark IT Solutions Pvt.Ltd.

SAP
•HANA
•BODS
• BOBI
•BW
Angular JS • BPC
• ABAP

Contact NBITS@ 9701000415


8977702468
ANGULAR JS MATERIAL
A Snvicc frnm '\!BITS

Tonics
1. HTML
2. HTML5
3. css
4. CSS3
5. JavaScri
6. Advan
7.
8.

N Benchmark IT Solutions Pvt.Ltd. contact on: 910100041s, 8911102468


#101, B-Block, Balaji Towers, Beside Prime Hospital, Near Mytrivanam, Ameerpet, Hyderabad
ANGULAR JS MATERIAL
A Service from NBITS

N Benchmark IT Solutions Pvt.Ltd. Contact0n:9701000415,8977702468


#101, B-Block, Balaji Towers, Beside Prime Hospital, Near Mytrivanam, Ameerpet, Hyderabad
ANGULAR JS MATERIAL
A Service from NRITS

Introduction to HTML
• HTML(Hypertext Markup language) is the language used to create web pages.
HTML language uses tags to create the web pages. Browsers read these tags to
display the output to the user.

• Note that html is interpreted browsers and hence we don't need to compile it.

What are HTML Tags?


Tags are Predefined keywords inside angular brackets.

Example : To represent body tag in html, we need


<body>. Now this is how we write body tag ins·

Example of other tags are <html>, <p>

Example
Let's consider th
bricks, tiles, pillars a er, and then we use cement and
create a building. Simi a terials like different tags and finally
add them up to

HT

N Benchmark IT Solutions Pvt.Ltd. contact on: 910100041s, 8911102468


#101, B-Block, Balaji Towers, Beside Prime Hospital, Near Mytrivanam, Ameerpet, Hyderabad
ANGULAR JS MATERIAL
A Service from NBITS

DOCTYPE Tag
Document Type Declaration or DOCTYPE declares which version of html is being
followed by the document. Note that doctype is not a html tag, it is just used to tell the
browser about the version of the html to follow for the current code. Note that
<!Doctype> should be the first tag in html code.

Jn html version, there are three types of DOCTYPES can be used :

• Strict

• Transitional

• Frameset.

Example:
This is an example BLIC "-
//W3C//DTD 4.01
Transitional//EN""http://www.w3.or

<head> tag
, link to scripts and metadata about
tag. Let's look at a code snippet
e> tag is contained inside head tag.

He
1.
2.
3.
4. t CSS is written inside this tag
5. s that JavaScript is written inside this tag

Examples for Meta Tags

keywords attribute defines keywords for search engines:


<meta name="keywords" content=" clothes, fashion, fashion accessories">

N Benchmark IT Solutions Pvt.Ltd. Contact On: 9701000415, 8977702468


#101, B-Block, Balaji Towers, Beside Prime Hospital, Near Mytrivanam, Ameerpet, Hyderabad
ANGULAR JS MATERIAL
A Service from NBITS

Description attribute describes your web page:


<meta name="description" content="Buy fashin clothes and accessories online" >

Revised attribute define the last revision of your page:


<meta name="revised" content="Hege Refsnes, 23/10/2011" >

http-equiv attribute Refreshes document every 10 seconds:


<meta http-equiv="refresh" content="lO">

First HTML Example


Open any editor of your choice or use notepad and type in the code shown below.
After typing it save it as first.html file and open it in a web browser. Hey.. ! you have
created first web page.

<html>

<body>

N Benchmark IT Solutions Pvt.Ltd. Contact0n:9701000415,8977702468


#101, B-Block, Balaji Towers, Beside Prime Hospital, Near Mytrivanam, Ameerpet, Hyderabad
ANGULAR JS MATERIAL
A ScrYicc from NBITS

<hl> Hi .. I am a heading</hl>

</body>

</html>

Understanding the code


Lets now dissect the code. The first tag is the root tag which is <html>.

All html files need to have <html> as the starting tag.

The body tag contains the tags that display the o


<hl> tag which is the headline tag. We have <hl>
largest font size and <h6> has the smallest.
Whatever content we write inside th ith bold
and increased font size. Next is the closin
tag.
Note that we add a slash in
tag, to end the tag we add a slash and it

Lets understand other ht

1. e opening and closing tag.

re tags which don't have a closing pair of tags.

Block Elemen Vs Inline Elements "

1. Block level tags: Block level tags add a line break for the content

Ex: <hl>, <p> for paragraph tags.

A block element will take the complete horizontal area of the web page. So, if you
add a block element, the next element will be placed in next line only.

N Benchmark IT Solutions Pvt.Ltd. Contact0n:9701000415,897770Z468


#101, B-Block, Balaji Towers, Beside Prime Hospital, Near Mytrivanam, Ameerpet, Hyderabad
ANGULAR JS MATERIAL
A Service from NBTTS

' ' i .. :

'--'.U:''·ii:lin::- d'l?me1:t 1</sp<1'n> : .2:em;


, ;: ..1:· ir.l.'..n.:, <:::l01f.E'Pt 2<f~,p~:r:'> ,,,: 0.b7f.>m;
: 0.67emj

2. lnline tags: Inline tags don't add a line break. Ex:


content in bold letters.

This is a block element

Par
al, but it's good to have the opening and closing tag.
o, i am a text inside paragraph</p> . Note that paragraph is a block

Links: To display a link we use the <a> tag.

Ex: <a href ="http://google.com ">Click to Google</ a>.

Here href is the source of the link. Notice that we have added a property to the tag
using a href keyword. We call these properties as attributes.

N Benchmark IT Solutions Pvt.Ltd. contact on: 910100041s, 8911102468


#101, B·Block, Balaji Towers, Beside PrimeHospital, Near Mytrivanam, Ameerpet, Hyderabad
ANGULAR JS MATERIAL
A Sl'n in· frnm NR ITS

<b> is for making text bold, <i> is for making text italic ,<em> for emphasizing a
text and <u> is for underline.

<img> tag is used to display an image. Note that it is a self closing tag. Means we
don't need to close it.

For <img> tag we have attributes namely width and height to adjust the height and
width of the image. Let's create a snippet of code to display an image, with a link and
some text formatting!

Example
Create a file with the name mypage.html and write t a comment
enclose the comment like this<!-- this is a commen

<!DOCTYPE HTML PUBLIC "-//W3C/l


"http:/ /www.w3.org/TR/html4 /loose.dtd"
<html>
<head>

</head>
<body>

ee the two line break below me!</em>

·mage.jpg" width = "200" height= "150">

<hr/>

<a href = "http://google.com">Google me</ a>

<!-- I am a comment and will not be visible in the page~

<hl> I am the bigges heading</hl>

<h2> I am the smaller heading</h2>

<h6> I am the smalles heading</h6>

N Benchmark IT Solutions Pvt.Ltd. Contact On: 9701000415, 8977702468


#101, 8-Block, Balaji Towers, Beside Prime Hospital, Near Mytrivanam, Ameerpet, Hyderabad
ANGULAR JS MATERIAL
·\ Snvil'l' fn;m NBITS

</body>

</html>

Creating Tables
HTML table can be considered as group of rows where each of them contains a group of
cells.

A table can be created using the below tags

• <table> element which acts as main container

• <tr> element which acts as row container

• <td> element which defines a single cell.

Let's look at an example of creating table in

Table Example

<table>
<tr>

</tr>
</table>
Ordered List Tags Example
<OL TYPE="l">
<LI> Item one </LI>
<LI> Item two </LI>
<OL TYPE="I" >

N Benchmark IT Solutions Pvt.Ltd. Contact0n:9701000415,8977702468


#101, B-Block, Balaji Towers, Beside Prime Hospital, Near Mytrivanam, Ameerpet, Hyderabad
ANGULAR JS MATERIAL
A Servin' frnrn '\BITS

<LI> Sublist item No one </LI>


<LI> Sublist item No two </LI>
<OL TYPE="i">
<LI> Sub-sublist item No one </LI>
<LI> Sub-sublist item No two </LI>
</OL>
</OL>
</OL>

Unordered Lists
<UL>
<LI> Item One </LI>
<LI> Item Two </LI>
<UL TYPE="circle">
<LI> Item Three </L

</UL>

HTML Forms
Forms are used to enter data and send the data to the server. Let's have a look at a
simple form example.

<form name= "myform.html" action = "submit.php" method= "GET"> First Name


<input type = "text" name ="first name">

N Benchmark IT Solutions Pvt.Ltd. Contact0n:9701000415,8977702468


#101, B-Block, Balaji Towers, Beside Prime Hospital, Near Mytrivanam, Ameerpet, Hyderabad
ANGULAR JS MATERIAL
A Service fr, '111 '\ 13 ITS
<input type= "submit" value= "submit me" name= "submit">
</form>

In the above example we have a form tag. The attribute name represents name of
the form tag, action represent the page to which the form data is sent and method
represent the way of data transfer. We have GET and POST methods.

Inside the form tag we have nested the input tag which c;reates a text box . Again
the input tag needs to have a name and type attribute t '~p... ent name and type
respectively.
Then we have the input with type as submit which
go ahead and write this form to test it yourself.

Input Types
There are many input types a e important input types are
text input, text area, select, checkb
1. input
• text




Meta Tags
Metadata is informat
The <meta> tag is kept inside the <head> element.
The <meta> tag provides metadata about the HTML document.
Metadata is not be displayed on the web page. It is used to provide information about
data to browsers, web services and search Engines!
Meta elements are typically used to specify page description, keywords and other
metadata.

N Benchmark IT Solutions Pvt.Ltd. Contact0n:9701000415,8977702468


#101, B-Block, Balaji Towers, Beside Prime Hospital, Near Mytrivanam, Ameerpet, Hyderabad
ANGULAR JS MATERIAL
A Service from NBITS

<div> Tag
The <div> tag defines a section of a web page. It is a block level tag.
You can use the DIV element to divide our web page into sections and to give properties
to the content using CSS(we will discuss about CSS in the next section)
Example:
<div>
<p>This is a paragraph</p>
</div>

<span> Tag

Span tag is similar to div tag but it'


go to next line if we classify it using span t

N Benchmark IT Solutions Pvt.Ltd. Contact0n:9701000415,8977702468


#101, B-Block, Balaji Towers, Beside Prime Hospital, Near Mytrivanam, Ameerpet, Hyderabad
ANGULAR JS MATERIAL
A Service from NBITS

TMLS

N Benchmark IT Solutions Pvt.Ltd. Contact0n:9701000415,8977702468


#101, B-Block, Balaji Towers, Beside Prime Hospital, Near Mytrivanam, Ameerpet, Hyderabad
i--
ANGULAR JS MATERIAL
A Service from NBITS

What Is HTMLS?
• Successor of HTML 4.01 and XHTML 1.1
• It comes with new tags, features and

Wondering what it takes'


• Any Text editor such ream weaver
• Modern browsers chrome, safari
• Prior knowled

<video>, <audio>, <source>,


<embed>, <mark>,<progress>,
<meter>, <time>, <ruby>, <rt>,
<rp>,<wbr>, <canvas>, <command>,
<details>,<summary>, <datalist>,
<keygen> and <output>

N Benchmark IT Solutions Pvt.Ltd. Contact0n:9701000415,8977702468


#101, B-Block, Balaji Towers, Beside Prime Hospital, Near Mytrivanam, Ameerpet, Hyderabad
ANGULAR JS MATERIAL
A Service from NBITS

HTML Structure
An HTML page first starts with the DOCTYPE declaration

<!DOCTYPE html>

<html>

<head>

<title>Title of the document</title>

</head>
<body>
That's all I need to create

</body>

</html>

Semantic
ANGULAR JS MATERIAL
·\ Srn IL'l' from NBITS

HTMLS Form
HTMLS not only makes marking up forms easier on the developer, it's also better for
the user.
With client-side validation being handled natively by the browser, there will be greater
consistency across different sites, and many pages will loa faster without all that
redundant JavaScript.

HTMLS Form Attributes


• <form> / <input> autocomplete Attrib
• <form> / <input> novalidate Attrib
• <input> autofocus Attribute
• <input> formaction Attribute
• <input> formmethod Attrib
• <input> formnovalidate Attribut
• <input> formtarget A
• <input> list Attrib


HT
at provide for more data-specific UI elements and native
l of 13 new input types:

Search
url tel
datetime date

month week time


datetime-local number
range co lo

N Benchmark IT Solutions Pvt.Ltd. Contact0n:9701000415,8977702468


#101, B-Block, Balaji Towers, Beside Prime Hospital, Near Mytrivanam, Ameerpet, Hyderabad
ANGULAR JS MATERIAL
A Snvice from NBlTS

HTMLS Form Elements

• <input type> keygen


• <input type> output

HTML Storage - I
• Web Storage simply provides
localStorage["name"] =username;.
• Unfortunately, present implement
mappings, so you need to seria
structures. You can do so usi SO
• Web SQL Database gives - of a structured
SQL relational database.
• Local Storage allo tent data to he user's computer, via
the browser. at a later date, any data saved to

HTMLSto
• between Web Storage and Web SQL

a st ightforward key-value mapping, but it supports


in lational databases, so searching objects matching a
partic "eld is fast; y u don't have to manually iterate through every object in
the store.
• File Access Pl for reading file content in JavaScript.
• Given a set des the user has added to a "file" input element, you can read
the content of the file or reference it as a URL, e.g. if the user has specified an
image file, you can show the image.
• There are also proposals underway for file writing capabilities.

HTML Geolocation
Geolocation allows your visitors to share their current location. Location are determined
by any of the following:

N Benchmark IT Solutions Pvt.Ltd. Contact0n:9701000415,8977702468


#101, B-Block, Balaji Towers, Beside Prime Hospital, Near Mytrivanam, Ameerpet, Hyderabad
ANGULAR JS MATERIAL
A Service from '.'BITS

• IP address
• Wireless network connection
• Cell tower
• GPS hardware on the device

Privacy Concerns

Not everyone will want to share their location with you, as there are privacy
concerns inherent to this information. Thus, your visitors must opt in to share their
location.

Nothing will be passed along to your site or web applicati


decision is made via a prompt at the top of the br

Geolocation Methods
These different tasks are ree methods currently available in the
Geolocation AP!:



<fi

<figure>
<img src="insect.jpg" alt="lnsect image">
<figcaption>Caption for the Insect image</figcaption>

</figure>

N Benchmark IT Solutions Pvt.Ltd. Contact On: 9701000415, 8977702468


#101, B-Block, Balaji Towers, Beside Prime Hospital, Near Mytrivanam, Ameerpet, Hyderabad
ANGULAR JS MATERIAL
A Sen ice rrnm :'\BITS

HTML Canvas
With HTMLS's Canvas AP!, we're no longer limited to drawing rectangles on our
sites. We can draw anything we can imagine, all through JavaScript.

<html>

<body>
<canvas width="SOO" height="300" id=" canvas"></ canvas>

<script>

var canvas =document.getElementB as');


var c =canvas.getContext('2d');
c.fillStyle = "Blue";

</script>

</body>

</html>

Line Styles:
f the end caps for a line
of corner created, when two lines meet

Re ct

Path:
stroke() Actually draws the path you have defined
beginPath() Begins a path, or resets the current path
movePath() Moves the path to the specified point in the canvas, without creating
a line

losspath() Creates a path from the current point back to the starting point.

N Benchmark IT Solutions Pvt.Ltd. Contact0n:9701000415,8977702468


#101, 8-Block, Balaji Towers, Beside Prime Hospital, Near Mytrivanam, Ameerpet, Hyderabad
ANGULAR JS MATERIAL
A Service from NBITS

Transforms:
scale() Scales the current drawing bigger or smaller
rotate() RoL1tes the current drawing
translate() Remaps the (0,0) position on the canvas
transform() Replaces the current transformation matrix for the drawing.

Understanding the coordinate System(XY


The coordinate system for browsers is different oordinate
system. It starts from the top left.

0,0
x

<script>
var canvas = document.getElementByld('myCanvas');
var context= canvas.getContext('2d');
context.rect(O, 0, canvas.width, canvas.height);
/ / add linear gradient
var grd = context.createLinearGradient(O, 0, canvas.width,
canvas.height):

N Benchmark IT Solutions Pvt.Ltd. Contact0n:9701000415,8977702468


#101, B-Block, Balaji Towers, Beside Prime Hospital, Near Mytrivanam, Ameerpet, Hyderabad
ANGULAR JS MATERIAL
A Service from ~BITS

/ / light green
grd.addColorStop(O, '#8ED600');

/ / dark green
grd.addColorStop(l, '#004COO');
context.fillStyle = grd;
context.fill();
</script

Canvas Radial Gradient


<canvas id="myCanvas" width="578" height="200"><
<script>
var canvas = document.getElementByl

context.rect(O, 0, canvas.wid
/ / create radial gradient
var grd = context.er . ·
/ / light green

</script>

SVG
SVG stands for Scalable Vector Graphics and it is a language for describing 2D-
graphics and graphical applications in XML and the XML is then rendered by an SVG
viewer

N Benchmark IT Solutions Pvt.Ltd. Contact0n:9701000415,8977702468


#101, B-Block, Balaji Towers, Beside Prime Hospital, Near Mytrivanam, Ameerpet, Hyderabad
ANGULAR JS MATERIAL
A Service from NBITS

• SVG images can be created and edited with any text editor
• SVG images can be searched, indexed, scripted, and compressed
• SVG images can be printed with high quality at any resolution
• SVG images are zoomable (and the image can be zoomed without
degradation)

HTML video Tags


HtmlS video tag is used to display videos.

<video controls>
<source
src="movie.webm"

<source

</video>

<audio>
<source
src="song.mp3" type="audio/mpeg"/>

</audio>

Modernizer

N Benchmark IT Solutions Pvt.Ltd. contacton:910100041s,s91110246s


#101, B-Block, Balaji Towers, Beside Prime Hospital, Near Mytrivanam, Ameerpet, Hyderabad
ANGULAR JS MATERIAL
A Service from NBITS
Modernizer, a tool for HTMLS verification of tags in HTMS and features.

• Modernizer is a small JavaScript Library that detects the availability of


native implementations for HTMLS Features and CSS.
• Modernizer provides an easy way to detect any new feature so that you can take
corresponding action.
• Just load the Modernizer script at the head section of DOM.

<script
src="modernizr.min.js"
type="text/javascript">
</script>

N Benchmark IT Solutions Pvt.Ltd. Contact0n:9701000415,8977702468


#101, 8-Block, Balaji Towers, Beside Prime Hospital, Near Mytrivanam, Ameerpet, Hyderabad
ANGULAR JS MATERIAL
A Service from NBITS

N Benchmark IT Solutions Pvt.Ltd. Contact On: 9701000415, 8977702468


#101, B-Block, Balaji Towers, Beside Prime Hospital, Near Mytrivanam, Ameerpet, Hyderabad
ANGULAR JS MATERIAL
A Service from NBITS

Introduction to CSS

CSS stands for Cascading Style Sheets. Prior to CSS the way to add styling like
color, alignment or background image was to add them as aur· s to the elements. But
this made the html code full of attributes making the code . So the styling part
was moved to CSS.

So CSS is the language for styling the HTML elem

Adding styling to tags

So how do we style the elements?

·n add a red color to a font inside a


paragraph element. T me code in CSS as shown below

<html>

<body>
<p> Hi..I am text inside a paragraph</p>
</body>
</html>

CSS example Explained

N Benchmark IT Solutions Pvt.Ltd. Contact0n:9701000415,897770Z468


#101, B-Block, Balaji Towers, Beside Prime Hospital, Near Mytrivanam, Ameerpet, Hyderabad
ANGULAR JS MATERIAL
First we have added <style> tag in the head section. Reason is that head section
loads before the body section of HTML. Note that we specify the type attribute as
type= "text/css" to tell browsers that the code is CSS.

Inside CSS code we mention the tag name we want to format and then add the properties
inside curly braces.

Structure of a style

What we created in the previous example is a style definition

Each style definition contains:

• A property
• A colon
• A value
• A semicolon to separate two or mo

A style definition can include one

p{font-size:12px; color:red}

Tag Selector

nt to red color and font size of 12px.

CSS Selectors

CSS selectors are used for selecting the content we want to style in HTML.
Like in the previous example we used a tag selector to select a tag to apply the styling.

CSS selectors are broadly classified into following categories


• Tag selector
• ID selector
N Benchmark IT Solutions Pvt.Ltd. Contact0n:9701000415,8977702468
#101, 8-Block, Balaji Towers, Beside Prime Hospital, Near Mytrivanam, Ameerpet, Hyderabad
ANGULAR JS MATERIAL
A Service from NBITS

• Clztss selector
• Mixed selectors which are combination of the above three.

ID Selector

All html tags can be given an ID to identify a specific element.

Ex: <p id= "para">Hello</p>

ID Selector is a part the CSS rule where an


So for styling the paragraph above we can u symbol
before the id and add the styling. See the co

#para{
color: red;
font-size: 20px;
}

ent. To classify a group of elements we


e used the class red-font to two elements
nam

· t add a dot before the class name and write the CSS rule. See the
example below.

red-font{
color:red
}
Using a class selector we can apply the same style to a group of html elements.

Types of Styles

Style are classified into three types

N Benchmark IT Solutions Pvt.Ltd. Contact On: 9701000415, 8977702468


#101, B-Block, Balaji Towers, Beside Prime Hospital, Near Mytrivanam, Ameerpet, Hyderabad
ANGULAR JS MATERIAL
A Service fr,,111 \i BITS

1. Embedded style: Embedded style has CSS rules kept inside the style tag in the
same html file. We have already covered the embedded example before.
2. Inline style: If style is written within the tag, it is called inline style
3. External style has CSS rules linked in a separate external file
Let's explore them now.

Embedded Style
<html>
<head>
<title>Getting Started</title>
<style type= "text/css">
p {font-family: sans-serif; color:
</style>
</head>
<body>
<p> Hi..I am text insi
</body>
</html>

Inline Style
Below is the example o ritten as attribute of tag.
<html>

sans-serif; color: orange;"> Hi..i am text

</html>

External Style
The example below is an example of external style sheet. All the styles are kept in
style.css
<html>
<head>
<style type ="text/ css" rel ="stylesheet" href ="sLyle.css"></ style>

N Benchmark IT Solutions Pvt.Ltd. Contact On: 9701000415, 8977702468


#101, 8-Block, Balaji Towers, Beside Prime Hospital, Near Mytrivanam, Ameerpet, Hyderabad
ANGULAR JS MATERIAL
A Service l'rom NBITS

</head>
<body>
<hl>hello</hl>
</body>
</html>

External style sheet is better


It's important to note that in development always use e)}tet[lal style sheet because
that helps to maintain style sheets. Having external style sl:iee.ts
,_.;:;,
h~lp maintain the DRY
principle(Don't repeat yourself).

We should avoid using embedded style sheets.


Using inline style sheets makes the html code m t.

Box Model
·. ·adding is the spacing
the padding. Margin is
surrounding space aroun

Have a look at the im

I run the content inside a di\~The


is the size of the

N Benchmark IT Solutions Pvt.Ltd. Contact0n:9701000415,8977702468


#101, 8-Block, Balaji Towers, Beside Prime Hospital, Near Mytrivanam, Ameerpet, Hyderabad
ANGULAR JS MATERIAL
A Service from NBJTS

Setting padding, margin


margin property is used to set the margin for an element. Use

margin:<top><top-right><top-bottom><top-left> Similarly: pa
right><top-bottom><top-Ieft> Ex:

hl{
margin: Spx 2px 3px Spx;
}

Alternatively we can use the following

hl{
margin-top:Spx; margin-
right:2px; mar ·
bottom:3p




For setting border sides we can use
• border-top
• border-bottom
• border-left
• Border-right

We can use the shorthand


border:<border-width><border-style><border-coior>

N Benchmark IT Solutions Pvt.Ltd. Contact On: 9701000415, 8977702468


#101, 8-Block, Balaji Towers, Beside Prime Hospital, Near Mytrivanam, Ameerpet, Hyderabad
ANGULAR JS MATERIAL
A Service from NRITS

hl{
border: Spx solid red
}

CSS Box Model


CSS Box model uses divs, margins and padding to create a complete web page
layout. The method of creating page layout using div is called ta

Prior to this, designer used tables to create web page layo


to use this approach because it gives a non uniform l t.

Inbuilt Browser styles


Every browser provides a set of inbuil

elps to give a better


browser has different

One way to solve this es like padding, margin etc to 0


and then giving the
A better alterna· · ne example is normalize.css library
which should to reset the default browser styles.

rty removes the element from the document flow and moves them
e float property.

float: left/ right / none

N Benchmark IT Solutions Pvt.Ltd. contacton:910100041s,s91110246s


#101, B-Block, Balaji Towers, Beside Prime Hospital, Near Mytrivanam, Ameerpet, Hyderabad
ANGULAR JS MATERIAL
A Service from NBTTS

Float property

The float property removes the element fr


edge specified in the float property.

As we have discussed before, div i


line break. But using float property w ight or left and inline
within the container.

float: left/ right / none

N Benchmark IT Solutions Pvt.Ltd. Contact0n:9701000415,8977702468


#101, 8-Block, Balaji Towers, Beside Prime Hospital, Near Mytrivanam, Ameerpet, Hyderabad
ANGULAR JS MATERIAL
A Service from NBITS

Problems with float

Float has one major problem. If we float any elements inside a container, then the
container doesn't expand as per the size of the inner elements.

There are 2 fixes for it. One fix is to keep clear the float of the last element. If the last
element also has to float, then we add a new empty div and set its property to float : none.
Have a look at the code used to float 2 images. One image floats to left and other floats to
right.

Clear-fix
We have a better solution for the float problem. Instead of just using a div, we can
use a clear fix class and add it to the container.

Have a look at the next code making use of clearfix.

N Benchmark IT Solutions Pvt.Ltd. Contact0n:9701000415,8977702468


#101, B-Block, Balaji Towers, Beside Prime Hospital, Near Mytrivanam, Ameerpet, Hyderabad
ANGUlJ\R JS MATERIAL
.\ Sen ice from NBITS

Clear-fix code

Div, Span
Every element has a default display value depending on what type of element it is.

N Benchmark IT Solutions Pvt.Ltd. Contact On: 9701000415, 8977702468


#101, B-Block, Balaji Towers, Beside Prime Hospital, Near Mytrivanam, Ameerpet, Hyderabad
ANGULAR JS MATERIAL
A Service from NBITS

The default for most elements is usuaJJy block or inJine.

div is the standard block-level element. A block-level element starts on a new line and
stretches out to the width of the container.

Example of other block-level elements are p and form,hl etc

span is the inline element. An inline element helps to wrap som text inside a paragraph
<span> like this </span> without disrupting the flow of t graph. The link <a>
element is one example

"Display" Property Block/Inline


CSS gives us the flexibility to cha
property.

For a block level element we ca


behave as inline element.
Similarly we can set the pro

page as though the element is not present

pt to hide or show elements without deleting


and

Setting displ none will render the page as though the element does not exist.
Visibility: hidden hi s the element, but the element takes up the space as it would if it
was fully visible.

margin: auto
#outer {
width: 600px;
margin: 0 auto;
}
N Benchmark IT Solutions Pvt.Ltd. Contact On: 9701000415, 8977702468
#101, B-Block, Balaji Towers, Beside Prime Hospital, Near Mytrivanam, Ameerpet, Hyderabad
ANGULAR JS MATERIAL
A SerYin· i"nirn NBITS

Setting the margin property to auto automatically aligns it to the center.


Note: We have given two values. 0 auto which means the top and bottom margins are 0
and left and right are auto. This is shorthand notation

max-width
#outer {
max-width: 600px;
margin: 0 auto;
}

Setting max-width property limits the stretch olution is


higher.
max-width instead of width improves t e
for making a site usable on mobile.

ment appears bigger than what we


set.

etches out the element beyond the specified

padding: 50px;
border-width: 10px;
}
In the code above, the actual width of the element is width+padding+border-
width. In this case the actual element width is 500+2*50+2*10 =620px

N Benchmark IT Solutions Pvt.Ltd. Contact0n:9701000415,8977702468


#101, B-Block, Balaji Towers, Beside Prime Hospital, Near Mytrivanam, Ameerpet, Hyderabad
ANGULAR JS MATERIAL
A Service fn>m "JRITS
• Solution: Developers have always just written a smaller width value than what they
wanted, subtracting out the padding and border. We will get a better solution when we
move to CSS3 .

"display" property block

Every element has a default display value dependin


The default for most elements is usually block or i
called a block-level element. An inline element is alw

div is the standard block-level elemen new line


and stretches out to the left and right as fa

Example of other block-level ele


footer, section etc

</div>
.burgerp {
background: brown;
}
p.cheese {
background: yellow;
}

N Benchmark IT Solutions Pvt.Ltd. Contact On: 9701000415, 8977702468


#101, B-Block, Balaji Towers, Beside Prime Hospital, Near Mytrivanam, Ameerpet, Hyderabad
ANGULAR JS MATERIAL
A Service frllm NBITS

.burger p: Note the space between .burger and p. This selects all the p elements inside an
element with the class burger.

p.cheese : Note that there is no space between p and .cheese. This selects the paragraph
with a class cheese.

Multiple Classes


each value is space separated.
• This way we can add additional s
<button class="btn notice">.
<button class="btn error"
.btn {
font-size: 16px;
}
.notice {

properties of both btn 'and ~otice class.

Keyword color values are names (such as red, green) that map to a given color

Keyword color values are simple in nature, however they provide limited options .

main{
background: maroon;

.nav{

N Benchmark IT Solutions Pvt.Ltd. Contact On: 9701000415, 8977702468


#101, B-Block, Balaji Towers, Beside Prime Hospital, Near Mytrivanam, Ameerpet, Hyderabad
ANGULAR JS MATERIAL
A Strvicl' fr<lm NBITS
background: yellow;

RGB Color

RGB color value is stated using the rgb() function,


blue.

This function accepts three comma-se ger from


0 to 255.

A value of 0 is pure black; a value of

.main{
background: rgb(
}
.nav{

RG

rgba() function.

This function uses a fourth value, which is a number between 0 and 1, including
decimals. Zero value creates a fully transparent colormaking it invisible, and a value of 1
creates a fully opaque color.

Values between 0 and 1 would create a semi-transparent color.

For shade of orange to appear 70% opaque, we would use an RGBa color value of
rgba(255, 102, 0, .7).

N Benchmark IT Solutions Pvt.Ltd. Contact0n:9701000415,8977702468


#101, 8-Block, Balaji Towers, Beside Prime Hospital, Near Mytrivanam, Ameerpet, Hyderabad
,---

ANGULAR JS MATERIAL
A Service from NBITS
.container {
background: rgba(128, 0, 0,.7);
}

HSL & HSLa Colors

HSL color values use the hsl()


lightness.

Within the parentheses, the function ac es, much


like rgb().

Returning to our shade of or


hsl(24, 100%, 100%).

HSL color values, Ii


with the use of the hsla

Absolute length values are the simplest length values, as they are fixed to a
physical measurement, such as inches, centimetres, or millimetres.

The most popular absolute unit of measurement is known as the pixel and is
represented by the px unit notation.
The pixel is equal to 1/96th of an inch; thus there are 96 pixels in an inch. The
exact measurement of a pixel, however, may vary slightly between high- density and low-
density depending on viewing devices.

N Benchmark IT Solutions Pvt.Ltd. Contact0n:9701000415,8977702468


#101, B-Block, Balaji Towers, Beside Prime Hospital, Near Mytrivanam, Ameerpet, Hyderabad
ANGULAR JS MATERIAL
A Service from NBJTS

div{
font-size: 14px;
}

Relative Length

Relative Lengths is not fixed units of measureme


another measurement.

We have percentages and ems for relativ

Percentage length is defined in rel r example,


to set the width of an element to 40%, we - arent element,
the element it is nested within, and t rent element's width

.main {
width:40%;
}

Relative I.:

r value for relative measurements.

an element's font size.

A single em eguivalent to an element's font size. So, for example, if an


element's font size pixels and has width set to 3em, the calculated width would
equal 72 pixels (24 pixels multiplied by 3.

Ex
.menu{
font-size: 24px;
width: 3em;
}

N Benchmark IT Solutions Pvt.Ltd. Contact On: 9701000415, 8977702468


#101, B-Block, Balaji Towers, Beside Prime Hospital, Near Mytrivanam, Ameerpet, Hyderabad
ANGULAR JS MATERIAL
i\ Snvicc from NBITS

Relative Lengths Percentage

The em unit is also a very popular relative value. T nit is represented by


the em unit notation, and its length is calculated based on a
A single em unit is equivalent to an element's i
element has a font size of 14 pixels and a width s Se
pixels (14 pixels multiplied by 5).

Ex
.banner{
font-size: 14px;
width: Sem;
}

practices to make website accessible and


her device(if required).

flexible to make content readable in different

Measuremen responsive design

Following are the points to note for making responsive websites:


1. Lengths should be specified in relative units like percentages and ems.
2. We should use media queries to change the CSS for different devices
3. Layout should be fluid and responsive.

N Benchmark IT Solutions Pvt.Ltd. Contact0n:9701000415,8977702468


#101, B-Block, Balaji Towers, Beside Prime Hospital, Near Mytrivanam, Ameerpet, Hyderabad
ANGULAR JS MATERIAL
A Servi<:e from NBJTS

Inheritance

Inheritance is the process by which some CSS properties applied to one tag are
passed on to nested tags. For example, a <p> tag is always nested in- side of the <body>
tag, so properties applied to the <body> tag get inherited by the <p> tag. Say you created
a CSS tag style.

Many CSS properties don't pass down to descendant tags at all. For example,
the border property (which lets you draw a box around an element) isn't inherited, and
with good reason.

A general rule is that properties that affect the


or the margins, background colors, and borders of

Cascading of Styles

erties get applied to an


element. It specifies how a le styles that apply to the
same tag and what to d en CS

> tag, a font size applied to a <p> tag, and a


g inside of a paragraph would inherit the font
graph.

e p for the following style

body { font-famil
p { color: grey; }
strong { font-size: 14

Cascading for Ancestors

What happens when inherited CSS properties conflict?

Nearest Ancestor Wins

N Benchmark IT Solutions Pvt.Ltd. Contact0n:9701000415,8977702468


#101, B-Block, Balaji Towers, Beside Prime Hospital, Near Mytrivanam, Ameerpet, Hyderabad
ANGULAR JS MATERIAL
.\ Sc'r\ JL'l' frnm NBlTS

Consider a page where We have set the font color for the body tag to red and the
paragraph tag to green. Now imagine that within one paragraph, there's <strong> tag.

The <strong> tag inherits from both the body and p tag styles, so is the text inside
the <strong> tag red or green? The green from the paragraph style.

That's because the style that's closest to the tag.

Specificity!

Try the following CSS and html code:

p.color-red{
color:red;
}
p{
color:green;
}

Below is html code( e added to the actual code)

font. As per the rule, the later style should override the
nt should be red?

e the specificity of first style is higher.

Specificity Score

So Here is the rule.


The pattern goes like that
<ID selector count>:<class selectors count>:< tags selector count>

N Benchmark IT Solutions Pvt.Ltd. contact on: 910100041s, 9911102468


#101, B-Block, Balaji Towers, Beside Prime Hospital, Near Mytrivanam, Ameerpet, Hyderabad
ANGULAR JS MATERIAL
A Snvil'l' l'rnm NBITS

Let's see with examples below


p.color-red{
color: red;
------- Specificity score is 0:1:1 because there are 0 id selectors, 1 class and 1 tag
selector
}

p{ color:green;
------- Specificity score is 0:0:1 because there are 0 id
selector
}
p #data div.color-red {
color: blue;
------- Specificity score is 1:1:2 because nd 2 tag
selector
}

Score Preference Rules

So rule is id score takes ond is class score and last is id score.


4:1. Similarly

the other selector with lesser

Using media eries, we can target CSS rules based on - for instance - screen size,
device-orientation or display - density. See the example below. The example below sets
the CSS property for elements only if the screen resolution min-width

@media (min-width: 481px) and (max-width: 768px){

.sidebar{
float:none;

N Benchmark IT Solutions Pvt.Ltd. Contact0n:9701000415,8977702468


#101, B-Block, Balaji Towers, Beside Prime Hospital, Near Mytrivanam, Ameerpet, Hyderabad
ANGULAR JS MATERIAL
A Scn·ice t'n1111 NBITS

border-top: Spx solid red;

padding-top: 10px;

N Benchmark IT Solutions Pvt.Ltd. Contact0n:9701000415,8977702468


#101, 8-Block, Balaji Towers, Beside Prime Hospital, Near Mytrivanam, Ameerpet, Hyderabad
ANGULAR JS MATERIAL
A Sen·ice from NBITS

Understanding CSS3

Successor of CSS2

• It comes with new modules


• With CSS3, you can create rounded borders, add
image as a border - without using a design program,
• Like HTMLS, CSS3 also has varied support ac

CSS 3 Gradients
CSS3 can be used to create gradient

• Gradients can be linear or radia .


• Linear gradients defin
• Radial gradient~ primary and
secondary color

N Benchmark IT Solutions Pvt.Ltd. Contact On: 9701000415, 8977702468


#101, B-Block, Balaji Towers, Beside Prime Hospital, Near Mytrivanam, Ameerpet, Hyderabad
ANGUlAR JS MATERIAL
A Service from NBITS

lransforms

CSS3 transform property lets you translate, rotate, scale, or s w any element on the
page.

div {
height: 100px; width:
100px; transform:
translate(80px, 80px)
scale(l.5, 1.5)
rotate( 45deg);
}

CSS properties to changeover time, essentially

For example, if changes color on hover, you can have it gradually fade from one
color to the other, of a sudden change.

Here are the steps to create a simple transition using only CSS:
• Declare the original state of the element in the default style declaration.
• Declare the final state of your transitioned element; for example, in a hover state.
• Include the Transition functions in your default style declaration, using few
different properties:
o Transition - property
o Transition - duration
o Transition - timing - function and
N Benchmark IT Solutions Pvt.Ltd. Contact On: 9701000415, 8977702468
#101, B-Block, Balaji Towers, Beside Prime Hospital, Near Mytrivanam, Anieerpet, Hyderabad
ANGULAR JS MATERIAL
A Service frnm NRJTS

o Transition - delay

div {
transition-property: color, left;
transition-duration: ls;
transition-timing: easy-in;
}

Animation
Transitions animate elements over time


animation via keyframes.
• CSS animations allow us in between, to
guide our animation in more com
• Animation properties

CSS3 Filters
Allows creating all these effects on images.

• Greyscale
• Blur
• Saturate
• Sepia
• Hue Rotate
N Benchmark IT Solutions Pvt.Ltd. Contact0n:9701000415,8977702468
#101, 8-Block, Balaji Towers, Beside Prime Hospital, Near Mytrivanam, Ameerpet, Hyderabad
ANGULAR JS MATERIAL
A Service from NBITS

• Invert
• Brightness
• Contrast
• Opacity
img{
filter: type( value);
-web kit-filter: type( value);
-moz-filter: type( value);
-ms-filter: type(value);
-a-filter: type(value);
}

Multi Column Layout

column-width: 15em;

padding: Spx; /*

CSS Background
Background properties includes

• background size, using more than one background for an element, and
N Benchmark IT Solutions Pvt.Ltd. Contact On: 9701000415, 8977702468
#101, B-Block, Balaji Towers, Beside Prime Hospital, Near Mytrivanam, Ameerpet, Hyderabad
ANGULAR JS MATERIAL
A Service from NBlTS

• Background origin (which effects the position of a background).


• Multiple Backgrounds
• The new ability to use multiple backgrounds is a great time saver, allowing
you to achieve effects which previously required more than one div.

Example:
url (example.jpg) top left no-repeat,
url( example2.jpg) bottom left no-repeat,
url( example3.jpg) center center repeat-y;

Box Model
• The width and height of any elem e CSS box
model.
• Without box-sizing

1 1px

N Benchmark IT Solutions Pvt.Ltd. Contact0n:9701000415,897770Z468


#101, 8-Block, Balaji Towers, Beside Prime Hospital, Near Mytrivanam, Ameerpet, Hyderabad
ANGULAR JS MATERIAL
.·\ Service from NBJTS

CSS Box Model with box-sizing


* { box-sizing: border-box; }

1 1px

ength of the item, relative to the rest of the flexible items

• The flex pro is a shorthand for the flex-grow, flex- shrink, and the flex-
basis properties.
• Syntax
flex: flex-grow flex-shrink flex-basislautolinitiall
inherit;

N Benchmark IT Solutions Pvt.Ltd. Contact0n:9701000415,8977702468


#101, B-Block, Balaji Towers, Beside Prime Hospital, Near Mytrivanam, Ameerpet, Hyderabad
ANGULAR JS MATERIAL
A Service from NBITS

CSS3 Flex Property Example


#main {
width: 200px; height: 100px; border: lpx solid #c3c3c3;

display: -webkit-flex; /* Safari */


display: flex;

-webkit-flex-direction: row-reverse; /*Safari 6


flex-direction: row-reverse; }

/*Safari 6.1 + */
#main div:nth-of-type(l) {-w

#main div:nth-of-ty

Selectors
Selectors are at the heart of CSS.
• Relational selectors
Descendant (E F)
Child (E > F)

N Benchmark IT Solutions Pvt.Ltd. Contact On: 9701000415, 8977702468


#101, B-Block, Balaji Towers, Beside Prime Hospital, Near Mytrivanam, Ameerpet, Hyderabad
ANGULAR JS MATERIAL
1\ Srn icL' l'rnm NBITS
Adjacent Sibling (E + F) General Sibling (E ~ F)

• Attribute selectors
E[attr$=val]
E[attr*=val]

Pseudo-class
• A pseudo-class is used to define a special state of an el~,we")
• For example, it can be used to: . f' · ·

Style an element when a user mouses over it


Style visited and unvisited links diff

• Syntax
selector:pseudo-class

:enabled

:valid
Applies to elements that are valid, based on the type or pattern attributes
:invalid
Applies to empty required elements, and elements failing to match the
requirements defined by the type or pattern attributes.
:in-range

N Benchmark IT Solutions Pvt.Ltd. Contact0n:9701000415,8977702468


#101, B-Block, Balaji Towers, Beside Prime Hospital, Near Mytrivanam, Ameerpet, Hyderabad
ANGULAR JS MATERIAL
Applies to elements with range limitations, where the value is within those
limitations. This applies, for example, to number and range input types with
min and max attributes

:out-of-range
The opposite of :in-range: elements whose value is outside the limitations of their
range.
:required
Applies to form controls that have the required attri
:optional
Applies to all form controls that do not h
:read-only
Applies to elements whose cont

Text Shadow

Syntax

x-offset
y-offset
blur-radius
color to set the color of the shadow

#style{
text-shadow: Opx -15px 0 #fe2192
}

N Benchmark IT Solutions Pvt.Ltd. Contact0n:9701000415,8977702468


#101, B-Block, Balaji Towers, Beside Prime Hospital, Near Mytrivanam, Ameerpet, Hyderabad
ANGULAR JS MATERIAL
A Service from NBITS

cript

N Benchmark IT Solutions Pvt.Ltd. Contact0n:9701000415,8977702468


#101, B-Block, Balaji Towers, Beside Prime Hospital, Near Mytrivanam, Ameerpet, Hyderabad
ANGULAR JS MATERIAL
A SnvirL' frnm NBITS

What is JavaScript?
JavaScript is a full-fledged programming language that can be applied to an HTML
document and used to create dynamic interactivity on websites.
It was invented by Brendan Eich, co-founder of the Mozill
Foundation and the Mozilla Corporation.

First JavaScript Program

The plus ( +) operator is used to concatena

<html>
<head>

"+name +"And age is "+age);

Variable
• Variables are containers that you can store values in.
• Declaring a variable with the var keyword, followed by any name you want to call
it:
Syntax: var variableName;

N Benchmark IT Solutions Pvt.Ltd. Contact0n:9701000415,8977702468


#101, 8-Block, Balaji Towers, Beside Prime Hospital, Near Mytrivanam, Ameerpet, Hyderabad
ANGULAR JS MATERIAL
A Service from NBITS

• Rule : They must begin with a letter or the underscore character.


• JavaScript is an untyped programming language.
• Semicolons in JavaScript terminates a statement.

Data Types
• JavaScript allows the same variable to contain different types of data values .
• Primitive data types
./ Number: integer & floating-point numbers
./ Boolean: logical values "true" or "false"
./ String: a sequence of alphanumeric characte
• Composite data types (or Complex data types)
./ Object: a named collection of data
./ Array: a sequence of values
• Special data types
./ Null: an initial value is assig
./ Undefined: the variable as

gJt','Stev~',10];
. .qr~ arraYilike this:.

N Benchmark IT Solutions Pvt.Ltd. Contact On: 9701000415, 8977702468


#101, 8-Block, Balaji Towers, Beside Prime Hospital, Near Mytrivanam, Ameerpet, Hyderabad
ANGULAR JS MATERIAL
A Service from NBlTS

Everything in JavaScript is a4 var


object, and can be stored in a myVariable=document.
variable. querySeh~ctor('hl ');

Note: $\lH>fthe above examples too.


,''"''' , ,,, uk

Operators

An operator is basically a mathematical ct on two values (or

variables) and produce a result.

• Arithmetic operators , + , - , / , * , %
• Logical operators && , 11 , !
• Comparison operators == , === , >= , <= ,
• String operators +
• Bit-wise operators & , ! , >>, <<
• Assignment operators += , -=

Conditional
ow to test whether an expression
de depending on the result.


if Statement
• It is the main conditional statement in JavaScript.
• The keyword "if' always appears in lowercase.
• The condition yields a logical true or false value.
• The condition is true, statements are executed.

Syntax: if {condition) {statements;}

N Benchmark IT Solutions Pvt.Ltd. Contact0n:9701000415,8977702468


#101, 8-Block, Balaji Towers, Beside Prime Hospital, Near Mytrivanam, Ameerpet, Hyderabad
ANGULAR JS MATERIAL
A Service frnm NBITS

if... else Statement


You can include an "else" clause in an if statement when,y(f" nt to execute some
statements if the condition is false.

Syntax:
if (condition) {statements;}

else { statements; }

else if Statement
Allows you to test for value and executes a particular
block of code.

Syntax:

if/if ... else statement

Syntax:
if (condition) {

if (condition) { statements; }

else { statements; }
N Benchmark IT Solutions Pvt.Ltd. Contact0n:9701000415,8977702468
#101, B-Block, Balaji Towers, Beside Prime Hospital, Near Mytrivanam, Ameerpet, Hyderabad
ANGULAR JS MATERIAL
A Service from NBITS
}

Switch statement
Allows you to merge several evaluation tests of the same vari
statements.
Syntax:

switch (expression) {

case labell:
statements; break;

default:
statements;



• "while" Loop
• "do ... while" Loop

for loop
• One of the most used and familiar loops is the for loop.
• It iterates through a sequence of statements for a number of times controlled by a
condition.

N Benchmark IT Solutions Pvt.Ltd. Contact0n:9701000415,897770Z468


#101, B-Block, Balaji Towers, Be~!~ Prime Hospital, Near Mytrivanam, Ameerpet, Hyderabad
ANGULAR JS MATERIAL
A Sl'n ic<: from NBITS

• The change_exp determines how much has been added or subtracted from the
counter variable.

Syntax:

for (initial_expression; test_exp; change_ exp)

{ statements; }

for -in loop


• When the for /in statement is used, the counter and ter
the length of the object.
• The statement begins with 0 as the initial value oft
with all the properties of the objects have been

E.g. array ITl no more elements found

Syntax:

{ statements;

while loop
• dition and keeps looping until the

• e context of the statements inside the curly

do while loop
• The do/while loop always executes statements in the loop in the first iteration of
the loop.
• The termination condition is placed at the bottom of the loop.

Syntax:

-
N Benchmark IT Solutions Pvt.Ltd. Contact0n:9701000415,8977702468
#101, 8-Block, Balaji Towers, Beside Prime Hospital, Near Mytrivanam, Ameerpet, Hyderabad
ANGULAR JS MATERIAL
A Sn\'icl' from NBITS
initial value declaration;

while (condition) {statements; increment/decrement statement;

Function
• A JavaScript function is a block of code designed to perform a particular task
• A JavaScript function is executed when "somethin " es it (calls it).

Syntax:
functionName(parameterl, parameter

code to be executed

How do we get more argu

• · n called arguments .

on", "Alice")// 'Hi, Ron', then 'Hi, Alice'

Scope
"Scope" refers to the variables that are available to a piece of code at a given time.

Functions have access to variables defined in the same scope

Example:
N Benchmark IT Solutions Pvt.Ltd. Contact On: 9701000415, 8977702468
#101, B-Block, Balaji Towers, Beside Prime Hospital, Near Mytrivanam, Ameerpet, Hyderabad
ANGULAR JS MATERIAL
A Sen Jn' frnm NBITS
var foo ='he lo';

var sayHello =function() {

console.log( foo );

};

sayHello(); //logs 'hello'

console.log(foo); //also logs 'hello'

Code outside the scope in which a variable was define .


variable

Example:
var sayHello =function() {var foo ='
};

sayHello(); //logs 'hello'

Scope
ifferent scopes with different values

var foo ='hello'; console.log(foo );


};

Debugging in JavaScript
With the recent boom of JavaScript, all major browsers come with their own debug tools.

Examples:
• Chrome has Chrome DevTools. You can access it by shortcut key Ctrl+Shift+Alt.
N Benchmark IT Solutions Pvt.Ltd. Contact0n:9701000415,8977702468
#101, 8-Block, Balaji Towers, Beside Prime Hospital, Near Mytrivanam, Ameerpet, Hyderabad
ANGULAR JS MATERIAL
A Scn·ice frnm \!BITS

• For Firefox you can use firebug extension.

DOM (Document Object Model)


A standard platform- and language-neutral programming interface for building,
accessing, and manipulating valid HTML and well-formed XML documents.

Ultimate goal is to make it possible for programmers to wr· · that work


properly on all browsers and servers, and on all platform

How DOM Works?

g,S="button_off.gif"

<head>
<~~~p!>
funs;SlQD. toggle()
Lf!9chJJ!t~J1!~Jwsi.:!>J1!:to

"button_on.gif";}

</script>

</head>

<\?,.QQY> <a br~f="test.ht I"


gnm~~r="toggle()"> <Lf!!Sl "'"-----> fil='ibutton_on.gif"
name="button1" ?lS="button_off.gif">
</a?:_~~Jbody>

N Benchmark IT Solutions Pvt.Ltd. Contact0n:9701000415,8977702468


#101, B-Block, Balaji Towers, Beside Prime Hospital, Near Mytrivanam, Ameerpet, Hyderabad
ANGULAR JS MATERIAL
A Service from J\:BITS

DOM Manipulation
document.getElementsByTagName(tagname)
This method returns a collection of all elements reference in the document with the
A/~:v
specified tag name.
document.getElementsByClassName( classname)
This method returns a collection of all elements t with the
specified class name.

Modifying HTML Using inn


lnnerHTML is the property of DO · rty we can get/set the
html inside a tag.
Example:

nclick ="addHeading()">Add Heading</button>

Events
.• JavaScript can also respond to events which can also be actions by the user.
• Example clicking on a element, hovering over an element are all actions by user and
JavaScript uses events which can react to these actions.
• JavaScript attaches a function called an event listener or event handler to a
specific event and the function invokes when the event occurs.

N Benchmark IT Solutions Pvt.Ltd. Contact0n:9701000415,897770Z468


#101, B-Block, Balaji Towers, Beside Prime Hospital, Near Mytrivanam, Ameerpet, Hyderabad
ANGULAR JS MATERIAL
A Servin- frnm ~Bil S

Events can be attached in the following ways


1. lnline HTML attributes
2. Adding to element properties with JavaScript
3. Using DOM Event Listeners

Inline HTML Elements


Events can be attached as attributes to the elements like this
<div onclick ="showMsg()">Click<div>

Adding to Element Properties


We can also assign a function to the onclick ave a look
at the code snippet below

};

The best way to ha events is to use the event listener approach. We can assign
listeners to th click event using the addEventListener() method.
ref.addEventListener( event.function)

Event Types
• Mouse Events - mouseup , mousedown
• Keyboard events - keydown , keyup
• window events -load, unload

N Benchmark IT Solutions Pvt.Ltd. contact on: 910100041s, 8911102468


#101, 8-Block, Balaji Towers, Beside Prime Hospital, Near Mytrivanam, Ameerpet, Hyderabad
------------- --"--~------~

ANGULAR JS MATERIAL
A Srrviet~ from NBITS

• Form events - focus ,change

Action Dialog
<script type="text/javascript">
function confirmDelete() {
var answer= confirm("Are you sure you want"
+"to delete this player?");
return answer
}

</script>

alue="Delete" onclick="return confirmDelete()" />

</form>

Form Validation
<script>
function validate() {
if (document.getElementByld("name").value.length == 0) {

N Benchmark IT Solutions Pvt.Ltd. Contact0n:9701000415,8977702468


#101, B-Block, Balaji Towers, Beside Prime Hospital, Near Mytrivanam, Ameerpet, Hyderabad
I
I

ANGULAR JS MATERIAL
A Service from NBITS
alert("Please complete the required fields\n" +
"and resubmit.");
return false;
}
return true;
}

Add Player:

* Name:
41 Email:

</script>
<h3>Add Player:<
-"return validate()" >

N Benchmark IT Solutions Pvt.Ltd. Contact0n:9701000415,8977702468


#101, B-Block, Balaji Towers, Beside Prime Hospital, Near Mytrivanam, Ameerpet, Hyderabad
ANGULAR JS MATERIAL
i\ Servi<:<· from NBITS

Javas

N Benchmark IT Solutions Pvt.Ltd. Contact On: 9701000415, 8977702468


#101, B-Block, Balaji Towers, Beside Prime Hospital, Near Mytrivanam, Ameerpet, Hyderabad
A~GULJ\R JS MATERIAL
A Service from NBITS

Introduction to Object Oriented

• Object-oriented programming allows you to reuse code without having to copy or


recreate it
• Many popular programming languages (such as jav
PHP, Ruby and Objective-C) support object- oriente "

Terminology

Namespace
A container which allows nality under a unique,
application-specific name.

Property

Met
. It is a subroutine or function associated with a class.

Constructor
A method called at t moment of instantiation of an object. It usually has the same name
as that of the class containing it.

Class
Defines the characteristics of the object. It is a template definition of variables and
methods of an object.

N Benchmark IT Solutions Pvt.Ltd. Contact0n:9701000415,8977702468


#101, 8-Block, Balaji Towers, Beside Prime Hospital, Near Mytrivanam, Ameerpet, Hyderabad
ANGULAR JS MATERIAL
/\ Sn,·icc from NBITS
Object
An Instance of a class.

Inheritance
A class can inherit characteristics from another class.

Encapsulation
A method of bundling the data and methods that use t

Abstraction
The conjunction of complex inheritance,
simulate a reality model.

Polymorphism
Poly means "many" Different classes might define
the same method or p

• Define th e once, and use it many times.


• A JavaScript on is executed when "something" invokes it (calls it).
• Syntax
function name(parameterl, parameter2, parameter3) {
code to be executed
return value;
}

N Benchmark IT Solutions Pvt.Ltd. Contact0n:9701000415,8977702468


#101, B-Block, Balaji Towers, Beside Prime Hospital, Near Mytrivanam, Ameerpet, Hyderabad
ANGULAR JS MATERIAL
/\ Service from NBITS

Anonymous Function
Sometimes you need a simple function without the need of assigning it to a name. This is
cailed a anonymous function

Example
var nums = [1, 4, 3, 2, 6, 2, O];

nums.sort( function(a,b){ return a-

Immediate Function
An immediatefunction is a function t in ed.

e is: ' + thisName );

function Ftimes() {
var FtimesObj =new Object()

function Ftimes3(x) {
return x * 3
}
function Ftimes4(x) {

N Benchmark IT Solutions Pvt.Ltd. Contact0n:9701000415,8977702468


#101, B-Block, Balaji Towers, Beside Prime Hospital, Near Mytrivanam, Ameerpet, Hyderabad
ANGULAR JS MATERIAL
A ScrYicr frnm NBITS
return x * 4
}

Ftimes0bj.Ftimes3 = Ftimes3
Ftimes0bj.Ftimes4 = Ftimes4
return FtimesObj
}

Multi =new Ftimes()


alert(Multi.Ftimes3(5)) //alerts 15

Closures
• A closure takes place when a funct" inds local
variables to it in such a way th
returned.
• A closure is a special kin o things: a function, and
any local variables that were in- sure was created.

e =getNameFunction();
alert( "Hello" + getName() + "!" );
return getName;
}(); //holds the getName() function
alert(displayName); //call it again later...
setTimeout( 'alert( "Your name is"+ displayName() )', 10 );

JavaScript Object Literal


N Benchmark IT Solutions Pvt.Ltd. Contact0n:9701000415,8977702468
#101, B-Block, Balaji Towers, Beside Prime Hospital, Near Mytrivanam, Ameerpet, Hyderabad
ANGULAR JS MATERIAL
A Sn,·in· from !\'BITS

• An object literal is a comma-separated list of name-value pairs wrapped in curly


braces.
• Object literals encapsulate data, enclosing it in a tidy package.
• This minimizes the use of global variables which can cause problems
When combining code.
Example
var myObject ={
sProp: 'some string value',
numProp: 2, bProp: false
};

• Sometimes we like to have an "o to create many objects


of one type.
use an object constructor
function:

er= new person("John", "Doe", 50, "blue");


other= new person("Sally", "Rally", 48, "green");

Private, Privileged, Public And Static Members

function Kid (name) { //Constructor

N Benchmark IT Solutions Pvt.Ltd. contacton:910100041s,s91110246B


#101, B-Block, Balaji Towers, Beside Prime Hospital, Near Mytrivanam, Ameerpet, Hyderabad
ANGULAR JS MATERIAL
A Service from NBITS

var idol= "Paris Hilton"; 11 Private


this.getldol =function () {return idol;}; I I Privileged
this.name =name; I I Public
}

11 Public
Kid.prototype.getName =function() {return this.name;};
I I Static property
Kid.town= "South Park";
/ / Create a new instance
var cartman =new Kid("Cartman");
I I Access private property
cartman.idol; /I undefined
I I Access privileged method

JavaScript Object Property


• Properties are the most important part of any JavaScript object.
• Properties are the values associated with a JavaScript object.
• A JavaScript object is a collection of unordered properties.
• Properties can usually be changed, added, and deleted, but some are read only.

N Benchmark IT Solutions Pvt.Ltd. Contact0n:9701000415,8977702468


#101, 8-Block, Balaji Towers, Beside Prime Hospital, Near Mytrivanam, Ameerpet, Hyderabad
ANGULAR JS MATERIAL
A Service from NBITS

Accessing JavaScript Property


The syntax for accessing the property of an object is:

• objectName.property
• objectName["property"]
• objectName [expression]

Enumerable Properties

• ws in some loop constructs,

tead of a superclass
rather than at the class level

Object4

Object3
. . PrnJK:
_proto_;.:
Object1 pn:tp3:
fn2:
ml:

~1:
fn1: ·
N Bt1u..11111a1I\.11 .;,u1uuu11;) r v l.LlU. Contact On: 9701000415, 8977702468
#101, B-Block, Balaji Towers, Beside Prime Hospital, Near Mytrivanam, Ameerpet, Hyderabad
ANGULAR JS MATERIAL
A Service from NBITS

Every object contains a reference to its prototype

• Default: Object.prototype; strings~ String.prototype; etc.

A prototype can have a prototype, and so on

• An object "inherits" all methods/data from its protot


• Doesn't have to make a copy of them; saves memor
• Prototypes allow JavaScript to mimic classes, i

Functions and Prototype

• example: when
Point.prototype
• initially this ob"
• every object s prototype object as its prototype

o be defined function Point(xValue, yValue) {

(Object)
Contains a reference to the internal prototype of the specified
object.__proto__

Parameters
object : Required. The object on which to set the prototype.
function Rectangle() {}

N Benchmark IT Solutions Pvt.Ltd. Contact0n:9701000415,8977702468


#101, B-Block, Balaji Towers, Beside Prime Hospital, Near Mytrivanam, Ameerpet, Hyderabad
ANGULAR JS MATERIAL
A Service from NBITS
var rec= new Rectangle();
if (console && console.log) {
console.log( rec. __ proto __ === Rectangle.prototype);

II Returns true
rec. __ proto __ =Object.prototype;
console.log( rec. __ proto __ === Rectangle.prototype);

11 Returns false
}

Prototypal Inheritance
• In JavaScript, the inheritance is pro re are no
classes. Instead, an object inherits f
• Inheritance, the __proto__

t_proto

other object animal, in

=animal.

Multiple Inheritances
Inheritance is all about copying properties from parent to child prototype, then why
not copy properties from multiple parents.

function multilnheritance() {

var n = {}, stuff, j =0, length =arguments.length;

N Benchmark IT Solutions Pvt.Ltd. Contact On: 9701000415, 8977702468


#101, B-Block, Balaji Towers, Beside Prime Hospital, Near Mytrivanam, Ameerpet, Hyderabad
ANGULAR JS MATERIAL
A Scn·ice from NBITS
for (j = O; j <length; j++) {
stuff= arguments[j];
for (var index in stuft) {
if (stuff.hasOwnProperty(index)) {
n[index] = stuff[index];
}

}
return n;

Parasitic inheritance
• This Pattern as suggest arasitic inheritance.
• It's about a functi y taking all of the functionality from
new object, and returning it.
• ypal inheritance which we have
used more often because its more

• the pro we get a new copy of it and assign that to MyCJass's


that changing the inherited properties will not affect the parent's
rties.
yClass.prototype = AnotherClass.prototy

function clone (obj) {


function CloneFactory () {} CloneFactory.prototype = obj;
return new CloneFactory();

N Benchmark IT Solutions Pvt.Ltd. Contact On: 9701000415, 8977702468


#101, B-Block, Balaji Towers, Beside Prime Hospital, Near Mytrivanam, Ameerpet, Hyderabad
ANGULAR JS MATERIAL
A Service from NBITS

• copy() makes a shallow, non-recursive copy of a single object. This


implementation is interesting because it handles native types and correctly copies
objects created by a user-defined class.
• deepCopy() is the entry point for the deep copy algorithm. Every
member is recursively deep copied.

Deep Copy
function deepCopy(p, c) {

c = c 11 {};
for (var index in p) {

N Benchmark IT Solutions Pvt.Ltd. Contact0n:9701000415,8977702468


#101, 8-Block, Balaji Towers, Beside Prime Hospital, Near Mytrivanam, Ameerpet, Hyderabad
ANGULAR JS MATERIAL

ery

N Benchmark IT Solutions Pvt.Ltd. Contact0n:9701000415,8977702468


#101, B-Block, Balaji Towers, Beside Prime Hospital, Near Mytrivanam, Ameerpet, Hyderabad
ANGULAR JS MATERIAL

Introduction to jQuery
• }Query is a fast and concise JavaScript Library.
• Simplifies HTML document traversing, event handling, animating, and Ajax
interactions for rapid web development.

Setting up jQuery
The best way to include jQuery is to include it fro
like Google CDN or Microsoft CDN as shown belo

Here we have included it from Google CDN

<head>

</script>

</head>

and download the jQuery 2.x

}Query Syntax ·

The jQuery syntax is tailor made for selecting HTML elements and performing some
action on the element(s).

Basic syntax is:

N Benchmark IT Solutions Pvt.Ltd. Contact0n:9701000415,8977702468


#101, B-Block, Balaji Towers, Beside Prime Hospital, Near Mytrivanam, Ameerpet, Hyderabad
ANGULAR JS MATERIAL
A Service from NBITS

• A$ sign to define/access jOuery


• A (selector) to "query (or find)" HTML elements
• A jOuery action() to be performed on the element(s).

Examples:
$(this).hide() - hides the current element.
$("p").hide() - hides all <p> elements.
$(".test").hide() - hides all elements with class="test".
$("#test").hide() - hides the element with id="test"

jQuery Example
<head>
<script src ="jquery.js"></s
</head>
<body>

Filtering Elements
The three most basic filtering methods are first(), last() and eq(), which allow you
to select a specific element based on its position in a group of elements.
Other filtering methods, like filter() and not() allow you to select elements that
match, or do not match, a certain criteria.
Example
$(document).ready(function(){
N Benchmark IT Solutions Pvt.Ltd. Contact On: 9701000415, 8977702468
#101, B-Block, Balaji Towers, Beside Prime Hospital, Near Mytrivanam, Ameerpet, Hyderabad
ANGULAR JS MATERIAL
A SerYicc !'rnrn NBITS
$("div p").first().css("background-color", "yellow");

});

Attribute Selector

The [attribute] selector selects each element with the specified att( · e.
c'.;:*cc/tf>t-1-cc

• To select all link tags that h

hat was just selected. Traversing can be broken down


, children, and siblings .


The metho for finding the parents from a selection include
.parent(), .par nts(), .parentsUntil(), and .closest()

• Children
The methods for finding child elements from a selection include
.children() and .find()

• Siblings
You can find previous elements with .prev(), next elements with .next(),
and both with .siblings().

N Benchmark IT Solutions Pvt.Ltd. Contact0n:9701000415,8977702468


#101, B-Block, Balaji Towers, Beside Prime Hospital, Near Mytrivanam, Ameerpet, Hyderabad
ANGULAR JS MATERIAL
A Service from NBJTS

JQuerylraversing Parent

<div class=" grandparent">

<div class="parent">

<div class=" child">

</div>

</div>

<div class="parent">
<div class=" child">
<span class="subchild"></span>

</div>
</div>

<div class="surrogateParentl II >< /d"IV>


N Benchmark IT Solutions Pvt.Ltd. Contact0n:9701000415,8977702468
#101, 8-Block, Balaji Towers, Beside Prime Hospital, Near Mytrivanam, Ameerpet, Hyderabad
ANGULAR JS MATERIAL
A Service from NBITS

<div class="surrogateParent2 11 ></d iv>

</div>
//Selecting an element's direct children:
//returns [parent, div.surrogateParentl, div.surrogateParent2]
$("div.grandparent" ).children( "div");

JQueryTraversing Sibling
<div class=" grandparent">

<div class="parent">

"></div>

}Query DOM Manipulation

There are many ways to change an existing element. Among the most common
tasks is changing the inner HTML or attribute of an element. }Query offers simple,
cross-browser methods for these sorts of manipulations.

N Benchmark IT Solutions Pvt.Ltd. contact on: 910100041s, 8911102468


#101, 8-Block, Balaji Towers, Beside Prime Hospital, Near Mytrivanam, Ameerpet, Hyderabad
ANGULAR JS MATERIAL
A Service from NBITS

append: Appends after html to the selected element.


prepend: Prepends before html to the selected element.
after: Adds html after the element.
before : Adds html before the element.
html : Replaces an existing html inside an element and adds the provided html.
remove: Removes an element from the DOM
addCss: Adds CSS class to an element
removeCss: Removes a CSS class to an element

}Query DOM Manipulation Example

• $("#target") .before("add da

}Query provides methods for assigning event handlers to elements in a cross-browser


way.

$('a').click(function( ev) {
$(this).css({background Color: 'orange'});
ev.preventDefault(); });

N Benchmark IT Solutions Pvt.Ltd. Contact On: 9701000415, 8977702468


#101, 8-Block, Balaji Towers, Beside Prime Hospital, Near Mytrivanam, Ameerpet, Hyderabad
ANGULAR JS MATERIAL
A Service from NBITS

Event - mouseover
]Query Example of mouseover event that shows a submenu when menu selected:

$('#menu').mouseover(function() {
$('#submenu').show();
});

}Query Forms

Selecting Form Elements


• Assign an ID to it
<input name="user" type="

(all form elements), :password, :radio,


:checkbox, :submit, :image, :reset, :button, :file, :hidden

• Can use descendant selectors too $('#signup : text')

Set the value of a form element


var fieldvalue =$('#total').val(Yourvalue);

N Benchmark IT Solutions Pvt.Ltd. Contact On: 9701000415, 8977702468


#101, 8-Block, Balaji Towers, Beside Prime Hospital, Near Mytrivanam, Ameerpet, Hyderabad
--1

ANGULAR JS MATERIAL
\ Ser\ ILL' i'rom NBITS

Determining if box is checked


If ($('#total').attr('checked')) {Do stuff if box is checked

else {
Do stuff if box is not checked
}

Form Event - Submit()

Example

$( document).ready(function

• Event delegation is an efficient way to watch for an event on a large number of


elements.
• Works by binding to a point farther up the DOM tree and watching for bubbling
events.
• jQuery has two ways to do event delegation
Jive() (as a direct replacement for .bind())
and .delegate().

• Works on all current, and future, elements.


N Benchmark IT Solutions Pvt.Ltd. Contact0n:9701000415,8977702468
#101, B-Block, Balaji Towers, Beside Prime Hospital, Near Mytrivanam, Ameerpet, Hyderabad
ANGULAR JS MATERIAL
A Service Crom NBITS

}Query -AJAX Introduction

• AJAX is the art of exchanging data with a server, and updating parts of a web page -
without reloading the whole page.
• ]Query provides several methods for AJAX functionality. With the jQuery AJAX
methods, you can request text, HTML, XML, or ]SON from a remote server using
both HTTP Get and HTTP Post - And you can load the external data directly
into the selected HTML elements of your web page!

}Query AJAX Method - load()

• The jQuery load() method is a si


method loads data from a server
element.
• Syntax:

is used to request data from the server with

ods for a request-response between a client and server

./ ests data from a specified resource


./ mits data to be processed to a specified resource
• The $.get() method requests data from the server with an HTTP GET request
• Syntax
$.get(URL,callback);

• The $.post() method requests data from the server using an HTTP POST request.
• Syntax:

$.post(URL,data,callback);

N Benchmark IT Solutions Pvt.Ltd. Contact0n:9701000415,8977702468


#101, 8-Block, Balaji Towers, Beside Prime Hospital, Near Mytrivanam, Ameerpet, Hyderabad
ANGULAR JS MATERIAL
/\ Sen il'L' frnm NBITS

}Query - noConflict()

Shortcut identifier, so that other scripts can use it. You can of course still use jQuery,
simply by writing the full name instead of the shortcut.

$.noContlict();

jQuery( document).ready(function(){

jQuery("button").click(function(){

jQuery("p").text("jQuery is still working!");


});

});

}Query Template

It allows you to easily conv

N Benchmark IT Solutions Pvt.Ltd. Contact On: 9701000415, 8977702468


#101, B-Block, Balaji Towers, Beside Prime Hospital, Near Mytrivanam, Ameerpet, Hyderabad
ANGULAR JS MATERIAL
A Sen·icc rrnm NBITS

}Query Promise

• Ajax supports only one callback function. Not only the jQuery $.ajax()
call, but also the underlying XMLHttpRequest object.

• Promise
Until jQuery 1.5, a typical $.ajax() call looked like this:

$.ajax({ url: "/myServerScript",


success: mySuccessFunction,
error: myErrorFunction });

The $.ajax() call returns a jQuery XMLHttp

• Since version 1.5, ommonJS Promises/ A


interface.
• CommonJS is a mmon and independent interfaces
(API's). Promi dvantage is that these are not
jQuery specif .
• Theway

N Benchmark IT Solutions Pvt.Ltd. Contact On: 9701000415, 8977702468


#101, B-Block, Balaji Towers, Beside Prime Hospital, Near Mytrivanam, Ameerpet, Hyderabad
ANGULAR JS MATERIAL
A Service from NBITS

N Benchmark IT Solutions Pvt.Ltd. Contact0n:9701000415,8977702468


#101, B-Block, Balaji Towers, Beside Prime Hospital, Near Mytrivanam, Ameerpet, Hyderabad
ANGULAR JS MATERIAL
<\ Servin: \i-<1m NBITS

What is Angular)s?
AngularJs is a front end framework for building structured and dynamic applications. It
internally uses JavaScript.

Why Angular)s?
Let's say we want to develop a single page application.

We know that in a single page application, the DOM load s · ppen only once. The
subsequent server side requests should be XHR reque modifying DOM using
JavaScript .To develop a big application which uses Java · t ext we need to
have an application structure and support for ba ST based
requests, managing templates, caching, security,

To solve our design problem, we can't


functions for generic tasks, But how a t th

• Application structure

• Managing the co

uirements we need a framework and Angularjs solves more than


ned above.

Angularjs Features

Following are the features which make AngularJs an ideal framework for developing web
applications

N Benchmark IT Solutions Pvt.Ltd. Contact0n:9701000415,8977702468


#101, 8-Block, Balaji Towers, Beside Prime Hospital, Near Mytrivanam, Ameerpet, Hyderabad
ANGULAR JS MATERIAL
A Service from NBITS

1. Providing structure to develop front end web applications, Angularjs has inbuilt
support for modules, controllers, factories, and services to modularize the code

2. Inbuilt support for Ajax and REST to communicate to the server.

3. Two way binding to data and view. This makes angular a great choice for
making interactive UI components quickly
4. Dependency Injection to inject the object required within the application
without again instantiating.
5. HTML compilation and inbuilt templating. Forget th s:-~·1;F"""1!£ft,"
take the headache of template compilation etc.
6. Fantastic support for Unit Testing. Angularjs Come
unit testing. The structure of angularjs applic

Getting started with Angular}

Download angularjs from =h=tt~¥-+=-=~


Note that you can also us ols like bower to set up angularjs from
command line.
·n the ript tag. Then we need to decide the
ply adding an attribute ng-app to any tag.
ing and ending of that tag that contains ng-

and angularjs will evaluate the expression and show the

What are angu rjs Expressions?

AngularJs Expressions are similar to JavaScript expressions that get evaluated within
double curly braces.

Ex: {{1+8}

N Benchmark IT Solutions Pvt.Ltd. Contact0n:9701000415,8977702468


#101, B-Block, Balaji Towers, Beside Prime Hospital, Near Mytrivanam, Ameerpet, Hyderabad
ANGULAR JS MATERIAL
A Service from NBITS

we can also write variable, objects and arrays inside like {{{employee.name}}
or {{product['name']}}

We can write JavaScript expression within these double curly braces and angularjs
evaluates them.

Ex:

<div ng-app>
<p>The addition of 1 and 5 is {{l +S}}</p>
<p >The multiplication of 1 and 5 is {{l +S}}</p
<p >The division of of 12 b 3 is {{12/3}}</

To display an object va e need to initialize the value .we


will be using a cus -init for this. Have a look at the
example below

<div ng-init ="


nd age are {{employee.name}} and
{{employee.age}}

</div>

N Benchmark IT Solutions Pvt.Ltd. Contact0n:9701000415,8977702468


#101, B-Block, Balaji Towers, Beside Prime Hospital, Near Mytrivanam, Ameerpet, Hyderabad
,--- ---------------------

I
ANGULAR JS MATERIAL
A Service from NBITS

Data binding

Data binding is one of the most useful features in <rngularjs.

Usual templating system have one way binding.

One way binding means that data is bound to the view once during rendering. Next time if
there is any change in the data, we have to again refresh the view to reflect

the data change. Let's have a look a the on way binding.

ay Data Bindin,g

• •
I
-~·

binding in Angularjs

Angularjs has two w y data binding. Means the data and the template view are in sync
every time. Any changes to the data instantly changes the view and vice versa.

The mechanism for this feature is as follows:

First the template which is the uncompiled HTML is compiled on the browser.

N Benchmark IT Solutions Pvt.Ltd. Contact0n:9701000415,8977702468


#101, B-Block, Balaji Towers, Beside Prime Hospital, Near Mytrivanam, Ameerpet, Hyderabad
I
I

A~GULAR JS MATERIAL
I A Service from NBITS

This compilation step produces a live view. Afterwards any changes to the view are
immediately reflected in the model, and any changes in the model are propagated to the
view.

Angularjs everytime keeps an eye and for any model change, it runs the cycle of updating
the view. This process is called dirty checking.

Next we will see the pictorial representation of two way Binding,


The two way data binding feature of angularjs keeps the el) in sync with the
view.

Two way data binding example

We will be covering model later. Fo we have a directive called


ng-model which makes an input coll r r example our model
is a simple text input. Any changes we e the value in the input box will get
reflected within the view w gularjs ssion. Below is the example

•I •
' ¥'*

Refer to binding.html
N Benchmark IT Solutions Pvt.Ltd. Contact0n:9701000415,8977702468
#101, B-Block, Balaji Towers, Beside Prime Hospital, Near Mytrivanam, Ameerpet, Hyderabad
~------- --~-- ------------·--------·-.-----------------

ANGULAR JS MATERIAL
'\Sn\ JLT from NBITS

<!doctypc html>
<html>
<head>

</head>
<body>
<!-- initialzing the app -->
<div ng-app>
<!--storing the value of input field into a variable name-->
<p>Name: <input type="text" ng-model="name"><
<p>{ {name} }</p>
</div>

Understanding AngularJS

of functionality .In angularjs we


app
arjs recommends us to organize our code
into modules. arts of code.
pplication. We can divide the application into
ayment, cart, product, user and all of these can
·es that we can create a payment module, user module and
so on.

Simple, just call the angular.module function as shown below

Vci.r userModuleReference = angular.module("userModule",[]);

Note that we have got a reference returned of the module instance in the variable user
Module Reference. The second parameter to the .module function is a comma separated
N Benchmark IT Solutions Pvt.Ltd. contacton:910100041s,s91110246s
#101, B-Block, Balaji Towers, Beside Prime Hospital, Near Mytrivanam, Ameerpet, Hyderabad
ANGULAR JS MATERIAL
A Sn' icl' rrom NBITS
value of modules required for the user Module. In this example the user module doesn't
depend on any module so we can write the empty square bracket there.

Understanding The main Module

If our application is a collection of many modules, then we also need a main module from
where we will initialize our application. Its just like the main method of Java, or c,c++.

To initialize our main module, we need to give the valuet:l


value of the main module. Lets say our main module i yA'

We can give a reference to myApp what


bootstraps the app using our module.

Retrieving the module

If any part of script dule, we need to call the module


method without t e mo

le('myModule',[]) creates the module and


retur le = angular.module('myModule') returns the
refe

Controllers

Controller is the function that adds variables and functionality to the scope of a view.We
can think of controller as a function that contains the business logic of the application.
Technically a controller is a JavaScript constructor function.

N Benchmark IT Solutions Pvt.Ltd. Contact0n:9701000415,8977702468


#101, B-Block, Balaji Towers, Beside Prime Hospital, Near Mytrivanam, Ameerpet, Hyderabad
ANGULAR JS MATERIAL
A Snvice i'rom NB!TS

Let's have a look at the example of a basic controller. Refer to basic_controller.html


<script type="text/javascript">
var my Module = anguslar.module('myModule', []);
myModule.controller('MyCtrl', function ($scope) {
$scope.location = "New York";
$scope.name ="smith";
});

</script>
</head>
<body>
<div ng-app="myModule"
<div ng-controller="MyCtrl">
<p>{{"Name is"+ name+" and loca ·

</div> </div>

Understandin

revious example.

and also a controller. Note that we define the

Modulereference.co lier( <controller-name>,<controller-function> ).

Next we pass a $scope object to the controller function. Note that $scope is an inbuilt
angularjs object that will contain the environment of the controller.

We can add any variables or even functions as properties to this $scope object. All the
properties and functions added to the $scope object are automatically available within
the element that has ng-controller value as value of the controller function name.

N Benchmark IT Solutions Pvt.Ltd. Contact0n:9701000415,8977702468


#101, 8-Block, Balaji Towers, Beside Prime Hospital, Near Mytrivanam, Ameerpet, Hyderabad
ANGULAR JS MATERIAL
A Snvirl' frnm "\BITS

Note that controller defines the body of the environment for the view.

To add a controller within the boundary of a DOM element, just add ng-controller
property with value as the controller name defined within the script. When angularjs
parses the entire html. It instantiates the controller object and defines the scope within
the DOM element boundry,,,ie starting and ending of the DOM element.

Note that we have attached two variables name and loc


become available within the div that has ng-contoller = "M

Attaching functions to controlle

As we have seen that we can atta oller. Similarly we can also


attach functions to the controller. to demonstrate how
can achieve it.

We will be using a ich can be added to any DOM


element to have a chc t to a~;, gn a click property to a button, just
add <button ng- ck= "di button>. The question is where we need to
define the di always attach it to the $scope va~iable
ow is the example

myModule.controller('MyCtrl', function ($scope) {


$scope.click= function(msg) {
alert(msg);
};

});

</script>
N Benchmark IT Solutions Pvt.Ltd. Contact On: 9701000415, 8977702468
#101, 8-Block, Balaji Towers, Beside Prime Hospital, Near Mytrivanam, Ameerpet, Hyderabad
ANGULAR JS MATERIAL
A Service from NRITS

</head>
<body>
<div ng-app="myModule"
<div ng-controller="MyCtrl">

<button ng-click="click('hello how r u')">Show Message</button>

</div>
</div>

Controller with function example


Lets have a look at one more example. Here w ct to the
scope and having an attached function to d' ithin the
object.

Refer to controllerwithfuncti

var myModule = an dule.controller('MyCtrl', function


($scope) {var da Ob =
"lastname": "

$sco
name.firstname);
};

});

</script>
</head>
<body>
<div ng-app="myModule"

<div ng-controller="MyCtrl">
<p>{{name.firstname + "" + name.lastname}}</p>

N Benchmark IT Solutions Pvt.Ltd. Contact0n:9701000415,8977702468


#101, B-Block, Balaji Towers, Beside Prime Hospital, Near Mytrivanam, Ameerpet, Hyderabad
ANGULAR JS MATERIAL
A Service from !\BITS

<button ng-click="click()">Show narne</button>

</div>
</div>

Using ng-model and data binding


The ngModei directive binds an input, select, text area or custom form control to a
property on the scope using controller. This is where user ~n enter data and it is
automatically updated in the view.
The ng-model directive gives us the flexibility of bind·
ngModel will bind the property given by evaluating t
If the property doesn't already exist on this scop
added to the scope.

Let's have a look at the example in

Using ng-model
e ng-model directive.
Also see the Ii alue in the text boxes and you can see the

r.module('myModule', []);

myModule.controller('MyCtrl', function ($scope) {


$scope.click =function() {
alert("first name is "+$scope.firstname+"and last name is "+$scope.lastname);
};

});

</script>

N Benchmark IT Solutions Pvt.Ltd. contact on: 910100041s, 8911102468


#101, B-Block, Balaji Towers, Beside Prime Hospital, Near Mytrivanam, Ameerpet, Hyderabad
ANGULAR JS MATERIAL
A Service from NBITS
</head>
<body>
<div ng-app= myModule
11 11

<div ng-controller= MyCtrl >


11 11

<p>Firstname: <input type= text ng-model="firstname"></p>


11 11

<p>Lastname: <input type= text" ng-model="lastname ></p>


11 11

<p>{{firstname + 11 11
+ lastname}}</p>

<button ng-click="click() >Show Name</button>


11

</div>
</div>

Understanding directives

comes up with inbuilt


to add behaviour and
functionality.

th behaviours and properties provided by


wn directives.
p to declare the main application. We will be
lear · In next slide, we will see a list of common

Follwing are the co

ng-click : To attach a click event.

ng-change: Fires a function when user changes input ng-init: to initialize data
ng-show: shows or hides the given HTML element based on the expression provided to
the ngHide attribute

N Benchmark IT Solutions Pvt.Ltd. contact on: 910100041s,s91110246s


#101, B-Block, Balaji Towers, Beside Prime Hospital, Near Mytrivanam, Ameerpet, Hyderabad
I
I

ANGULAR JS MATERIAL
A Service from NBITS

ng-href: to point a url for a link

ng-include: This directive fetches, compiles and includes an external HTML snippet. ng-
model: to bind a form input .
ng-repeat:This directive is used to repeat the html for a particular collection.Useful to
show an array items in a list etc.

ng-selected:If the expression value is true, then special a


on the specified element.

ng-show:lt shows or hides the given HTML e provided


to the ng-show attribute.

Understanding Scopes
Now that we know how to, d attach a s ope lets understand more
about scopes.
Every part of an A cope which is within the ng-app
boundry.
have prototypal inheritance, meaning that

find within the controller scope? In this case,

cope and or the property or method there. If Angular JS it can't find


"twill walk to that scope's parent and so on till it reaches
at an example to understand scopes further.

$rootscope

N Benchmark IT Solutions Pvt.Ltd. Contact0n:9701000415,8977702468


#101, 8-Block, Balaji Towers, Beside Prime Hospital, Near Mytrivanam, Ameerpet, Hyderabad
ANGULAR JS MATERIAL
/\ Sen ice from NBITS
Every module has a single root scope. All other scopes are descendant scopes of the root
scope. Scopes provide separation between the model and the view.

Note that $rootscope may be different for different modules.

The data set in $rootscope is available to all the controllers within the application.

Ok so the question is .. how do we set the value in a root scope? Yes,, we can definitely set
the value within a controller, But that will only effect the root scope value for that
particular controller. The changed value will not reflect in other controllers!

Here comes the run function of a module to our rescue. When er the module loads, it
runs the run function before loading any controllers and i · ea! place to set the
values within rootscope.

Example:

Refer to rootscope.html

<script type="text/javascript">

var myModule = angular.module('m

myM odule.run(function($rootScope )f

$rootScope.appName = "Te

})

});

o', function ($scope) {

$scope.lastname =

});

</script>

</head>

<body>

<div ng-app="myModule">

<p>{{"The application name is"+appName}}</p>

N Benchmark IT Solutions Pvt.Ltd. Contact0n:9701000415,8977702468


#101, B-Block, Balaji Towers, Beside Prime Hospital, Near Mytrivanam, Ameerpet, Hyderabad
ANGULAR JS MATERIAL
.'\ Service from NBITS
<div ng-controller="DataCtrlOne">
<p>Name is {{firstname +"" + lastname}}</p>
<p>The Modified application name is {{appName}}</p>
</div>
<div ng-controller="DataCtrlTwo">
<p>Name is {{firstname +"" + lastname}}</p>
<p>The application name is {{+appName}}</p>
</div> </div>

Scopes Hierarchy

What happens if we keep one controller

controller.

t controller and child controller.


Not mside the parent controller element becomes the

ild controller within parent controller in view to demonstrate how


inheritance works. hat when child controller is present inside parent controller it is
able to access the pr erty first name.

We have also kept child controller in view outside the main controller and in this case the
child doesn't inherit the first name property.

Have a look at example controller_inhertiance.html.

N Benchmark IT Solutions Pvt.Ltd. Contact0n:9701000415,8977702468


#101, B-Block, Balaji Towers, Beside Prime Hospital, Near Mytrivanam, Ameerpet, Hyderabad
ANGULAR JS MATERIAL
.·\ Sn1 in· J'rnm NBITS

Refer to controller_inhertiance.html
<script type= "text/javascript">
var myModule = angular.module('myModule', []); myModule.controller('MyCtrl',
function ($scope) {var model= { "firstname": "Jack",
"lastname": "Smith"};

$scope.model = model;
});

myModule.controller('ChildCtrl', function ($scope) {


var modelchild = {"hobby": "Tourism", "interests": "coding;i };
;<:?";\

$scope.company = "Google";
$scope.modelchild = modelchild;
});

</script></head>
<body>
<div id = "boundry" ng-app="

.C,'t
stname"></p>

="child" ng-controller = "ChildCtrl"> Your


first name is {{model.firstname}}

</div>
</div>
-controller= "ChildCtrl">
Your hobby is {{modelchild.hobby}} your first name is {{model.firstname}}

</div></ div>

Using $parent keyword

N Benchmark IT Solutions Pvt.Ltd. Contact0n:9701000415,897770Z468


#101, 8-Block, Balaji Towers, Beside Prime Hospital, Near Mytrivanam, Ameerpet, Hyderabad
ANGULAR JS MATERIAL
i\ Sn\'in· frnrn NBITS

Angul<ir scopes include a variable called $parent thC1t refers to the parent scope of a
controller. If a controller is at the root of the application, then parent would be the root
scope .. ic $rootscope

There are instances when we have overwritten the property of the parent controller
within child controller and we still want to access or modify it. In this case we can use
the $parent keyword.
Lets have a look at this with an example .. refer to keyword_$parent.html

<script type="text/javascript">
var myModule = angular.module('myModule', []);
myModule.controller('MyCtrl', function ($scope) {
$scope.name= "Smith";
});
myModule.controller('ChildCtrl', function

$scope.name= "John";
});

</script></head>
<body>
<div id = "boundry"

his is name property of child {{name}}

We have seen that can $scope injectable to give access to the data within the html.
Though this works fine, we can also use the this operator of the controller instance to
achieve the same.
The benefit of using this operator is that we don't need to use the $scope to attach data to
the scope. Let's see how it works with an example given below.

Example Using this operator within controller

N Benchmark IT Solutions Pvt.Ltd. Contact0n:9701000415,8977702468


#101, B-Block, Balaji Towers, Beside Prime Hospital, Near Mytrivanam, Ameerpet, Hyderabad
ANGULAR JS MATERIAL
A Service frn111 NBITS

Refer to controller_this.html
<script src="angular.js" type="text/javascript">

</script>
<script type="text/javascript">
var myModule = angular.module('myModule', []);
myModule.controller('MyCtrl', function() {
var model= { "firstname": "jack", "lastname": "Smith"};
this.model = model; this.click= function() { alert($scope.mo
};

});

</script>
</head>
<body>
<div ng-app="myModule">
<div ng-controller="MyCtrl
<p>Firstname: <input

r for nested controllers

The benefit of using this notation shines when using nested controllers. Note that can
refer to the parent and child using the alias we define within the html.
Let's see the example in the next section where we have parent controller and child
controller. Note that parent and child is defined by which controller is nested in the html.

Using this for nested controllers

N Benchmark IT Solutions Pvt.Ltd. Contact On: 9701000415, 8977702468


#101, B-Block, Balaji Towers, Beside Prime Hospital, Near Mytrivanam, Ameerpet, Hyderabad
ANGULAR JS MATERIAL
A Service frnm 1\CBITS

Refer to controller_this_inheritance.html
<script type="text/javascript">

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


myModule.controller('MyCtrl', function () {var model= { "firstname": "Jack",
"lastname": "Smith" };

this.model =model; this.click= function() { alert($scope.model.fjrstname);


};

});

myModule.controller('ChildCtrl', function () {var


"interests": "coding"};

this.company ="Google"; this.modelchild {


alert(this.modelchild.hobby);
};

});

</script>
</head>
<body>

</div>

pe="text" ng-model="parent.model.firstname"></p>
<p>Lastname: <input type="text" ng-model="parent.model.lastname"></p>
<p>{{parent.model.firstname + "" + parent.model.lastname}}</p>
your hobby is {{ child.modelchild.hobby}}
<div id= "child" ng-controller = "ChildCtrl as child"> Your hobby is
{{child.modelchild.hobby}}
your first name is {{parent.model.firstname}}

N Benchmark IT Solutions Pvt.Ltd. Contact0n:9701000415,8977702468


#101, B-Block, Balaji Towers, Beside Prime Hospital, Near Mytrivanam, Ameerpet, Hyderabad
ANGULAR JS MATERIAL
A Service from NBITS
</div>
<button ng-click="child.click()">Show Narne</button>
</div>
</div>

Inbuilt filters in Angularjs


Below is the list of inbuilt filters
1. Filter
2. Currency
3. Number
4. Date
5. }son
6. Lowercase
7. Uppercase
8. LimitTo
9. Orderby

Filters

the data we display to the user. There are


rjs. we can as well as an easy way to create

we simply need to put a pipe after the text or data we


filter name.
e expression. After filter we can optionally specify
One inbuilt filter is er with name uppercase. This filter as the name shows converts
the lowercase letters to the uppercase. Belw is the usage to use it
{{"smith" !uppercase}} . Let's see a simple usage of a filter
Refe to basic_uppercase_filter.html
<script type="text/javascript">
var myModule = angular.module('myModule', []);
</script>

N Benchmark IT Solutions Pvt.Ltd. Contact0n:9701000415,8977702468


#101, B-Block, Balaji Towers, Beside Prime Hospital, Near Mytrivanam, Ameerpet, Hyderabad
ANGULAR JS MATERIAL
A Service from NBITS

</head>
<body>
<div ng-app="myModule"
<p> Name in uppercase is {{"smith" Iuppercase} }</p>

</div>

Note that we can pipe in filters. Means we can apply more than filter. Just add the pipe
and call the filter.

Using filter within Javascript

Filters can also be used within the javascri


$filter( <filter-name>') (<expression>)

<script type="text/javascript">

$scope.name = $filte
});

</script>

<bo

</div>

</div>

Passing Arguments to Filters using currency filter

N Benchmark IT Solutions Pvt.Ltd. Contact0n:9701000415,8977702468


#101, B-Block, Balaji Towers, Beside Prime Hospital, Near Mytrivanam, Ameerpet, Hyderabad
ANGULAR JS MATERIAL
A Service from NBITS
For arguments, we can pass them with a colon after the filter name and for multiple
arguments, we append a colon after each argument.
Lets understand this using a currency filter

This filter Formats a number as a currency

{{ currency_expression I currency: symbol: fractionSize}} Below is the code(filename is


currency_filter.html)

<script>

angular.module('myModule', 0)

.controller('ExampleController', ['$scope', '$filter

$scope.amount= 1234.565555;

}]);

</script>

</head>

<inp

an id="currency-default">{{amount I currency

custom currency ide 1fier (USO$): <span id=" currency-custom">{{ amount I


currency:"USD$":3}}</span>

</div>

Using Number Filter


The number filter is used to filter numbers. This number filter Formats a number as
text.
N Benchmark IT Solutions Pvt.Ltd. Contact On: 9701000415, 8977702468
#101, B-Block, Balaji Towers, Beside Prime Hospital, Near Mytrivanam, Ameerpet, Hyderabad
,----- "-I
I i
ANGULAR JS MATERIAL
A Service from NBITS

If input is not a number an empty string is returned.

If input is an infinite then the Infinity symbol 'co' is returned

Below is the syntax

{{ nurnber_expression I number : fractionSize}} Below is thee

<script>

angular.module('myModule', [])

.controller('NumberController',

$scope.val= 2345.978777899;

}]);

</script>

</head>

r: <input ng-model='val'><br>

{{val I number:O}}</span><br> Displaying a


}</span>

Using Date
date to a string based on the requested format. Template format

{{ date_expression I date: format: timezone}}

Note that data can be either an ISO date object or date string or timestamp

Ex( refer to file date_filter.html):

<span>{{1288323623006 I date:'yyyy-MM-dd HH:mm:ss Z'}}</span><br>

N Benchmark IT Solutions Pvt.Ltd. Contact0n:9701000415,8977702468


#101, B-Block, Balaji Towers, Beside Prime Hospital, Near Mytrivanam, Ameerpet, Hyderabad
ANGULAR JS MATERIAL
.'\ Sn\ ice rrnm NBITS

Using )son Filter


The ]son filter allows to convert a JavaScript object into JSON string and is mostly
useful for debugging

Ex:

{{ json_expression I json : spacing}}

Note that spacing option is the number of spaces to use p


2

Refer to example json_filter.html

<script>

angular.module('myModule',

};

}]);

{{valljson}}

</div>

Limit filter
This filter creates a new array or string containing only a specified number of elements
as mentioned in the limitto filter. If we use a number as input, it is converted to a string.

N Benchmark IT Solutions Pvt.Ltd. Contact0n:9701000415,8977702468


#101, B-Block, Balaji Towers, Beside Prime Hospital, Near Mytrivanam, Ameerpet, Hyderabad
ANGULAR JS MATERIAL
.\ ScrYil'l: from NBITS

Syntax:

{{ limitTo_expression I limitTo : limit: begin}} or

$filter('limitTo')(input, limit, begin)

Below is the example(refer to number_limit.html)

<script>
angular.module('mainModule', [])
.controller('LimitController', ['$scope', function($~

$scope.numbers = [1,2,3,4,5,6,7,8,9,12,14];
$scope.numLimit = 2;
}]);

</script>
</head>
<body ng-app = 'main

tep="l" ng-model="numLimit">

We can use limit for strings too. Below is the example showing the different
usages. Refer to file r _limitto_usages.html

<script>
angular.module('mainModule', [])
.controller('LimitController', ['$scope', function($scope) {
$scope.numbers= [1,2,3,4,5,6,7,8,9,12,14];

$scope.letters = "lets see how many characters are displayed with limit";

$scope.longNumber = 1232345432342;

N Benchmark IT Solutions Pvt.Ltd. contacton:910100041s,s91110246s


#101, B-Block, Balaji Towers, Beside Prime Hospital, Near Mytrivanam, Ameerpet, Hyderabad
ANGULAR JS MATERIAL
A Snvicc' !'mm NRrI S

$scope.numLimit = 4;
$scope.letterLimit = 5;
$scope.longNumberLimit = 5;
}]);

</script>
</head>
<body ng-app = 'mainModule'>
<div ng-controller="LimitController">
Limit {{numbers}} to: <input type="number" step="2" ng-
<p>Output numbers: {{numbers I limitTo:numLi
Limit {{letters}} to: <input type="number" st
<p>Output letters: {{ letters I limitTo:lett
Limit {{longNumber}} to: <input typ
model="longNumberLimit">

</div>

OrderBy

r strings and numerically for numbers.


ure that numbers are actually being saved as numbers

low( refer to orderby_basic_filter.html)

<script>
angular.module('orderByApp', [])
.controller('OrderByController',function($scope) {
$scope.friends =
[{name:'Smith',phone:'SSS-1512', age:20},

N Benchmark IT Solutions Pvt.Ltd. Contact0n:9701000415,8977702468


#101, B-Block, Balaji Towers, Beside Prime Hospital, Near Mytrivanam, Ameerpet, Hyderabad
ANGULAR JS MATERIAL
{name:']ohn', phone:'SSS-6676', age:29},
{name:'Ajay', phone:'SSS-6621', age:31},
];

});

</script>
<div ng-app = "orderByApp">
<div ng-controller="OrderByController">
<table>
<tr>
<th>Name</th>
<th>Phone Number</th>
<th>Age</th>
</tr>
<tr ng-repeat="friend in friends I orde
<td>{{friend.name}}</td> </td> <td>{ {if'fend.age}}</td>

</tr>
</table>
</div>

Usi
· ter. It selects a subset of items from array and returns it

Here filter_expression is the expression, expression parameter represents the reference


data to which we have to filter and the comparator is the comparison function or value to
decide if the value can be considered a match.

Lets see a simple example below


<script>
var app = angular.module('searchModule',O);

N Benchmark IT Solutions Pvt.Ltd. Contact0n:9701000415,8977702468


#101, B-Block, Balaji Towers, Beside Prime Hospital, Near Mytrivanam, Ameerpet, Hyderabad
ANGULAR JS MATERIAL
A Service frnm NBITS

</script>
</head>
<body ng-app = 'searchModule'>
<div ng-init="friends = [{name:'john', phone:'555-1276'},
{name:'Manish', phone:'800-1234'},
{name:'Sumit', phone:'SSS-4321'},
{name:'Aadi', phone:'SSS-5678'},
{name:'Tyler', phone:'555-8765'},
{name:'Bantu', phone:'555-5678'}]"></div> Search: <inpu
<table id="searchTextResults">
<tr><th>Name</th><th>Phone</th></tr>
<tr ng-repeat="friend in friends I filter:se
<td>{{friend.name}}</td> <td>{{fri
</tr>
</table>

example, the filtering happens also for objects


previo xample, we can search for the phone number and
feature of this filter.

How about making a strict search. Means that only if the full value is a match, the data is
returned.
How to use? Simple use friend Obj in friends I filter:searchData:true
Note that the last parameter can be an expression also

Custom filters
N Benchmark IT Solutions Pvt.Ltd. Contact0n:9701000415,8977702468
#101, B-Block, Balaji Towers, Beside Prime Hospital, Near Mytrivanam, Ameerpet, Hyderabad
ANGULAR JS MATERIAL
A Service frnm NBITS

We can also create custom filters to meet custom requirements. Below is the syntax
ModuleRef.filter(' Custom- Fi Iter-N ame' ,function() {

return function( optional-parameter){


return modifiedValue;

}
});
Lets have a look at the example code. We are creating a
Good Morning to the string.( refer to basic_custom_f t
<script type="text/javascript">
var app = angular.module('myApp',[]);
app.filter(' greet' ,function(){
return function( name){

}
});

</script>
</head>

<div
me:'tiya'}, {name:'Luke'}, {name:'Mac'}]">

<ul>
<Ii data-ng-repeat="customer in customers">{{

customer.name Igreet }}</Ii>

</ul>
</div>

Filtering Arrays
N Benchmark IT Solutions Pvt.Ltd. Contact0n:9701000415,8977702468
#101, B-Block, Balaji Towers, Beside Prime Hospital, Near Mytrivanam, Ameerpet, Hyderabad
ANGULAR JS MATERIAL
A Service from NBJTS

We can also create a custom filter to filter arrays. Lets have a look at the following
example to see the implementation.
We are creating a filter named strlnS that filters elements with string length <=5 refer
to filter_custom_example.html).
<script type="text/javascript">
var app = angular.module('myApp',[]);
app.filter('strlnS ',function(){
return function(items){
var filtered = [];
for (var i = O; i <items.length; i++) {
var item= items[i];
// check if the individual Array element is l
filtered.push(item );
}
}
return filtered;
}

})
</script>

<bo

<ul>
<Ii data-ng-repeat="customer in customers I strlnS">{{customer.name }}</Ii>

</ul></div>

Exploring config and run function for module


We have 2 functions namely config and run function for the module.

N Benchmark IT Solutions Pvt.Ltd. contact on: 910100041s, 8911102468


#101, 8-Block, Balaji Towers, Beside Prime Hospital, Near Mytrivanam, Ameerpet, Hyderabad
ANGULAR JS MATERIAL
A Service from NBITS

The config function is the first function that runs when the module loads. After the
config function, the run function runs. See the console messages below to see the cycle
of load.
Lets see this with the example below

<script>

angular
.module('main', ['modulel', 'module2'])

.config(function () { console.log("came here config main mod


.run(function () { console.log("came here run main modu
.controller('M ainController' ,function(){
console.log("inside MyController of main");
});

angular
.module('module 1 ', ['module2 '])
.config(function () {console.log(" came h
.run(function () {console.I

. angular

fig of module2");})

</s

</div>

Explaining the Example for config and run functions


Lets understand the previous example.
We have the main module which has 1 dependency namely modulel.

The modulel again has dependency of module2.

N Benchmark IT Solutions Pvt.Ltd. Contact On: 9701000415, 8977702468


#101, 8-Block, Balaji Towers, Beside Prime Hospital, Near Mytrivanam, Ameerpet, Hyderabad
ANGULAR JS MATERIAL
\ Service from NBJTS

Note that main module has modulel dependency. Again the modulel has module2
dependency. Therefore first the module2 config function will run followed by config
function of modulel and finally the config function of main module will run.
Similarly the run function of the module2 followed by run function of modulel and then
the main module's run function.
Finally the controller of the main function will run.
Note that we can only inject one dependency which is a provider.

Note that At this phase, we can not inject either servic ctories because the
dependency injector has not instantiated the services and f
We can initialize all the configuration parameters in

At run phase we can inject all the depen


hence are available to be used.

Routing

We need routing hat is a route for AngularJs


Application?
Say we have it has 3 pages namely home, contacts and
controllers when the user navigates from
ching a click even to the menu item also, but it
is n
menu items, then a user can not navigate to the other

A teal single page a


Consider the home page url is mysite.com. To navigate to contact us we can make a url
like mysite.com/#contact us which will naviate the page to the contact us. We call them as
hash bang urls.

To implement routing we can use ngRoute module. Note that to use this module we need
to download the module JavaScript file and add it to the page.

N Benchmark IT Solutions Pvt.Ltd. contact on: 910100041s, 8911102468


#101, B-Block, Balaji Towers, Beside Prime Hospital, Near Mytrivanam, Ameerpet, Hyderabad
ANGULAR JS MATERIAL
A Service from NBITS

Next we have to include the ngRoute module in dependency array while declaring the
module.

Routing example
Refer to routing/routingexample.html.
<script>
var module= angular.module("sampleApp", ['ngRoute']);
module.config(['$routeProvider', function($routeProvider
$routeProvider. when('/routel/:param', {
templateUrl: 'templates/templatel.html',
controller: 'RouteController'
}). when('/route2/:param', {
templateUrl: 'templates/template2.
}).

otherwise({ redirectTo: '/', t


controller:'lndexControl
});
}]);

ction($scope, $routeParams) {

})

oiler' ,function($scope) {

$scope.message= "Welcome to home page";

})
</script>
</head>
<body ng-app="sampleApp">

<a href="# /routel/abcd">Route 1 </a><br />


N Benchmark IT Solutions Pvt.Ltd. Contact0n:9701000415,8977702468
#101, B-Block, Balaji Towers, Beside Prime Hospital, Near Mytrivanam, Ameerpet, Hyderabad
ANGULAR JS MATERIAL
:\ Scn1cc frnm NBITS

<a href="#/route2/1234">Route 2</a><br/>


<div ng-view></div>

</body>

Routing example explained


First that config is the function that runs first when the module loads. We can set up the
configuration for our module within this injecting the $route
Provider and setting up the routes here.

Next every route has a controller associated with it · .


navigates to the route. Corresponding to the route we.hav ·.
for the route. We use the ng-view directive hei:e. . \.vhj~h is't template
provided for routing. Below is the code taken f fu the ~;xample when('/ro :param',
{
templateUrl: 'templates/template2.html',

})

The following code is fire s above are found. We have loaded the
index page data here.

});

Dependency where dependencies for a component are


provided by the
Consider the examp $scope variable which is made available whenever required by a
controller. But the qu stion is how is the variable automatically made available?

The answer is dependency injection where the Angular injector injects the
$scope variable wherever it is required. We can inject dependencies at many places
within our angular code.
We have already seen that there are many variables available to use whenever we require
them. $scope is one such variable.

N Benchmark IT Solutions Pvt.Ltd. Contact0n:9701000415,8977702468


#101, B-Block, Balaji Towers, Beside Prime Hospital, Near Mytrivanam, Ameerpet, Hyderabad
ANGULAR JS MATERIAL
i\ Sen in- frnm NBITS

We can also inject the objects that we want to be made ;wailable using services which we
will be covering in the next section.

The three ways to inject dependences are Services, Factories and Providers.

Creating Services
We can create a singleton JavaScript object using a service. This object contains a set of
functions where can put the logic and use it. Using services we can separate common
logic and provide it to the controllers or other components. R
dependency_injection/service.html
<script>
~,,-,,AA,' ,

var serviceExample = angular.module('serviceExan}pl§';


serviceExample.service('wordService', functio P this.reverseWord = func (input) {
var result= "";

input =input 11 "";


for (var i=O; i<input.length; i++) {
result = input.charAt(i) + re
}

return result;

}
});

oller('MyCtrl' ,function ($scope, word Service) {


ordService.reverseWord ($scope.name);
$scope.$watch ('name' ,function (oldVal,newVal){

$scope.reversename = wordService.reverseWord($scope.name);

})

$scope.capitalizeName =function(){
$scope.reversename = wordService.capitalize($scope.reversename);

N Benchmark IT Solutions Pvt.Ltd. contact on: 910100041s, 0911102468


#101, B-Block, Balaji Towers, Beside Prime Hospital, Near Mytrivanam, Ameerpet, Hyderabad
ANGULAR JS MATERIAL
A Servin· frnm /\;BITS

});

</script>

</head>
<body ng-app = "serviceExample">
<div ng-controller = "MyCtrl">
<input type= "text" ng-model ="name"> Name in reverse is: {{reversename}}

<button ng-click = "capitalizeName()">Capitalize</button>

</div>

Services Example explained


In previous example we created a service two function. One to 'verse the
word and other to covert into capital lett functions caft'J!v:nf~~e reusable
,,;;:o·/
by attaching them to a service as in the
Its important to understand t or service of anuglarJs
automatically instantiates the constru <treates an object. That
object can be injected withi object is the same as the
name of the service. us· now access all instance functions(ie
functions referred usi
h wa es the changes in the value of name.
rses name by calling the function in the

within our controller.

Re repeatable logic within our controllers.


rvices for better re usability and code separation.

Creating factories
We can also create a singleton object using a factory. Refer to
dependency_injection/factory.html script>
var factoryExample = angular.module('factoryExample', []);

factoryExample.factory('wordFactory', function() {
var literalObject = { reverseWord :function(input) {var result = "";

N Benchmark IT Solutions Pvt.Ltd. Contact0n:9701000415,8977702468


#101, 8-Block, Balaji Towers, Beside Prime Hospital, Near Mytrivanam, Ameerpet, Hyderabad
ANGULAR JS MATERIAL
A Service frllrn NBJTS
input= input 11 "";

for (var i=O; i<input.length; i++) {


result= input.charAt(i) + result;
}
return result;
},

capitalize :function(input){
return input.toUpperCase(); }
}
return literalObject;
});
factoryExample.controller('MyCtrl' ,func
$scope.reversename = wordFacto

})

}
});

<inputtype ="text" ng-model ="name"> Name in reverse is: {{reversename}}


<button ng-click = "capitalizeNameQ">Capitalize</button></div>

Factory Example explained


A factory is similar to the service that it also provides a singleton JavaScript object using
angular dependency injection.

N Benchmark IT Solutions Pvt.Ltd. Contact0n:9701000415,8977702468


#101, B-Block, Balaji Towers, Beside Prime Hospital, Ne;ir _Mytrivanam, Ameerpet, Hyderabad
ANGULAR JS MATERIAL
A Service from NBITS
The difference between a factory and service is that in a factory we can return our own
custom object instead of the instantiated object of the function.
In the example we have created object literal, added functions to it and returned it. Note
that we did not attach functions to the function instance using this operator
The example logic is the same as of services example.

Creating Providers
We can also create providers. Providers are again singletons more configurable.

<script>
var providerExample = angular.module('providerEx
providerExample.provider('word', function() {
this.name= 'Default';
this.$get =function() {var name =this a
sayHello: function() {

}
}
};

this.setName -

};
});

});
providerExample.controller('MyCtrl' ,function ($scope, word) {
$scope.displayMessage =function(){
alert(word.sayHello());
}

});

N Benchmark IT Solutions Pvt.Ltd. Contact0n:9701000415,8977702468


#101, 8-Block, Balaji Towers, Beside Prime Hospital, Near Mytrivanam, Ameerpet, Hyderabad
ANGULAR JS MATERIAL
A Service from NRITS

</script>
</head>
<body ng-app = "providerExample">
<div ng-controller ="MyCtrl">
<button ng-click = "displayMessage()">Display Message</button>

Provider Example explained


A provider is advanced and configurable. A provider is
services in the aspect that It can be configured at the con
in the config function.
The function within the this.$get is instanti ector. To
demonstrate this we have created a functio message
appended by name variable. This vari function .
Important point to note is that the setN
not available to the singleton .tJ: injectible named
wordProvider in the config function.
Note that we always have t ing to the na e of the provider that we
created to inject it at t the name of the provider is word so
the name of the obje r. Notice that at the config phase
we get the full instance can call the setName function and
set the name v
e function sayHello will append the value

Directives
We have already gone through directives. Lets again revise. A directive is a custom tag,
attribute, class or comment that adds behaviour to html.
Ex: Instead of creating entire HTML and source for a cart button, we can create a tag
named <cart/> .
If you place <cart/> tag in your HTML source , you will get full functionalities of the cart.
Lets start with creating a simple directive to understand how we can create directives.

N Benchmark IT Solutions Pvt.Ltd. Contact0n:9701000415,8977702468


#101, B-Block, Balaji Towers, Beside Prime Hospital, Near Mytrivanam, Ameerpet, Hyderabad
,-
I
I

ANGULAR JS MATERIAL
A SL'rvice from NBITS

In the example below we create a custom directive tag called hello. When angular loads,
it compiles the tag and displays "Hi There" message in a div. Refer to example
directives /basic_d irective.html.

<body>
<hello></hello>
<script>
var appModule = angular.module('app', []); appModule.direcf
return {
restrict: 'E',
template: '<div>Hi there</div>', replace: true
};
});

</script>
</body>

. ate a ective we call the function directive


s the name of the directive and the second
ect contains all the settings of the directive.

}
The directive definit10n object contains many properties like restrict which had a value E
means that the directive is a html element. Next is the template property that is replaced
with the directive. If we give value ofreplace property as true, it will replace the directive
with the html in the template. If we set this value to false, then the html of template
property will be put
Inside the directive tag.refer to example directives/directive_replace_Value_false.html.

The full Directive API


N Benchmark IT Solutions Pvt.Ltd. Contact On: 9701000415, 8977702468
#101, B-Block, Balaji Towers, Beside Prime Hospital, Near Mytrivanam, Ameerpet, Hyderabad
ANGULAR JS MATERIAL
A Service from NBITS
Below is the full directive AP! with all properties. var appModule =
angular.module('appModule',[]);
appModule.directive('namespaceDirectiveName', function factory(injectables) {

var directiveDefinitionObject ={
restrict: string, priority: number, template: string, templateUrl: string, replace: bool,
transclude: boo!, scope: boo! or object,
controller: function controllerConstructor($scope,
$element,
$attrs,
$transclude), require: string,
link: function postLink(scope, iElement, iAttrs) {. lement,
tAttrs, transclude) {
return {
pre: function preLink(scope, iElemen
postLink(scope, iElement, iAttrs, co
}
}
};

});

restrict property
The restrict property declares if the directive can be used in a template as an element,
attribute, class, comment, or any combination.

N Benchmark IT Solutions Pvt.Ltd. Contact On: 9701000415, 8977702468


#101, B-Block, Balaji Towers, Beside Prime Hospital, Near Mytrivanam, Ameerpet, Hyderabad
ANGULAR JS MATERIAL
.\ SL'n ice from NBITS

See the list below

Character

Declaration Type Example

E element <hello
title=Products></hello>

A attribute <div

c class
u:Products></ d

M directive: menu
Products -->

What if you bination of behaviours. Say you want to to


an attribute~ Simply pass EA as the restrict

Creating a directive as attribute, element and class


Lets create a custom directive with name custom-dir that can be used as comment,
attribute as well as element.

N Benchmark IT Solutions Pvt.Ltd. contacton:910100041s,s91110246s


#101, B-Block, Balaji Towers, Beside Prime Hospital, Near Mytrivanam, Ameerpet, Hyderabad
ANGULAR JS MATERIAL
A SL'rvicc from NBITS
Note that our directive name is custom-dir in html view, however if there is a hyphen, we
need to remove it and the first character should be capital. Ex in our case for cusom-dir,
the name in directive declaration is customDir. Refer to
directives/ di rective_restrict_variations.html
<body>

<custom-dir></ custom-dir>
<br>
<p custom-dir></p>
<br>
<h3 class= "custom-dir"></h3>
<script>
var appModule = angular.module('app', []);
appModule.directive('customDir', functio
return {
restrict: 'EAC',

template: '<div> <h4>HI</


replace: true
};

});

</script>

e priority
Directives have p roperty. In case there are multiple directives in an element, the
directive with the hi priority gets applied first.

If we have multiple directives on a single DOM element and If the order in which they're
applied matters, we can use the priority property to order their application.

Note that Higher number priority directives run first. The default priority is 0 if we don't
specify one.
Ex for ng-repeat, we use a priority value of 1000.

N Benchmark IT Solutions Pvt.Ltd. contact on: 910100041s, 8911102468


#101, B-Block, Balaji Towers, Beside Prime HospitaJ, Near Mytrivanam, Ameerpet, Hyderabad
ANGULAR JS MATERIAL
A Sn, ice !'mm '.\:'BITS

Understanding Template property


Directives have priority property. In case there are multiple directives in an element, the
directive with the higher priority gets applied first.

If we have multiple directives on a single DOM element and If the order in which they're
applied matters, we can use the priority property to order their application.

Note that Higher number priority directives run first. The defaufpriority is 0 if we don't
specify one.
Ex for For ng-repeat, we use a priority value of 1000.

Understanding Template prope


We can replace or wrap the contents of a a html that We'~provide in the
template property. We have already s example

We wrote a
provided.

ntent to elements. We usually 1set replace

Usi

The template p rty has a drawback of getting the html code in the JavaScript code. A
better approach is the html code in a separate html file. We achieve this using the
template Uri proper
Let's see the example below (refer to directives/external_template.html)

<script src="angular.js" type="text/javascript"></script>


<script>
var appModule = angular.module('app', []); appModule.directive('externalTemplate',
function() { return {

N Benchmark IT Solutions Pvt.Ltd. Contact0n:9701000415,8977702468


#101, B-Block, Balaji Towers, Beside Prime Hospital, Near Mytrivanam, Ameerpet, Hyderabad
ANGULAR JS MATERIAL
.'\ Sl'n 1L'l' i"r,1111 \!BITS

restrict: 'E',
templateUrl: 'templates/external_template.html', replace: true
};

})

</script>
<body ng-app="app">
<external-template></external-template>
</body>

Transdusion
We can also move the original content wit ransclude
property.

"ginal content e directive, but make


it available for reinsertion w· through a dir ive called ng-transclude.
See the example below( re de.html)

<body>
><p> i am a paragraph</p></div>

, []); appModule.directive('hello', function() {

restrict:'A',
template: '<div> <h3 ng-transclude></h3></div>', transclude: true,

replace: true
};

});

</script>
</body>

N Benchmark IT Solutions Pvt.Ltd. Contact0n:9701000415,8977702468


#101, B·Block, Balaji Towers, Beside Prime Hospital, Near Mytrivanam, Ameerpet, Hyderabad
ANGULAR JS MATERIAL
A Service from NBITS

Scopes
Three types of scopes available for directives

1. The existing scope of our directive's DOM element.


2. Anew scope We can create that inherits from our enclosing controller's scope.

Here, we will have the ability to read all the values in the scopes and this scope
will be shared with any other directives on our DOM element that request this
kind of scope and can be used to communicate with the
3. An isolate scope that inherits no model properties fr
option when we need to isolate the operation of
scope usually while creating reusable compo

Using existing scope


GYej;,"
To create existing scope we set the v lu lse.S ee the "'exam p Ie (refer to
directives/parentscope_directive.ht

Note that in this example from parent. Also note that any change
we do to the parent pro es the parent property.

<script>

return {
restrict: "A", scope: false,
template: "<div>Your name is: {{name}}"+
"Change your name witht the input: <input type='text' ng-model='name' /></div>",
replace:true
};

N Benchmark IT Solutions Pvt.Ltd. Contact On: 9701000415, 8977702468


#101, 8-Block, Balaji Towers, 8eside Prime Hospital, Near Mytrivanam, Ameerpet, Hyderabad
ANGULAR JS MATERIAL
A Service frnm NB ITS

});

</script>
</head>
<body ng-app = "app">
<div ng-controller="Ctrl 1 ">
<h2 ng-click="alertName()">Hi {{name}}, Click to alert your name</h2>
<div test-directive></ div> </div>

Creating new scope with inheritance


If we set the scope value to true, it creates a new roperties
from the parent. However unlike the previous ive scope
and parent scope are not linked. Means e will not
change the parent property. Lets see in th

In the same example change the scope d test it again. Please


refer to the example directiv

s a new scope by inheriting parent scope.


reflect back to
the parent scope will

With scope set alse", the parent controller and directive are using the same scope
object. This means anges to the controller or directive will be in sync.

Create isolated scope


Isolate scopes doesn't inherit model properties, they are still children of their parent
scope. Like all other scopes, they have a $parent property that references their parent.

N Benchmark IT Solutions Pvt.Ltd. Contact On: 9701000415, 8977702468


#101, 8-Block, Balaji Towers, Beside Prime Hospital, Near Mytrivanam, Ameerpet, Hyderabad
ANGULAR JS MATERIAL
A Service from NBITS

When you create an isolate scope, you don't have access to anything in the parent scope's
model by default. You can, however, specify that you want specific attributes passed into
your directive. You can think of these attribute names as parameters to the function.

To create a isolate scope we just need to write scope:{} in the DDO( directive definition
Object).

The new scope also known as isolated scope because it is completely detached from its
parent scope.

Communicating in isolate scope


We have 3 modes in which we can communica ithin our
directive for an isolated scope. Angularjs give
we want to inherit from the parent and at w
binding) .This way we can selectively choo

Following are the modes

l."@"

2. "="

One way text


We can create text bindings which are prefixed with @. They are always strings.
Whatever we write as attribute value, it will be parsed and returned as strings. Note that
we need to keep the parent property value inside an expression. le inside double curly
braces. Lets see the example below(refer to directives/oneway_binding_text.html). Refer
to the next slide for explanation

<script>

N Benchmark IT Solutions Pvt.Ltd. Contact On: 9701000415, 8977702468


#101, 8-Block, Balaji Towers, Beside Prime Hospital, Near Mytrivanam, Ameerpet, Hyderabad
ANGULAR JS MATERIAL
A Service from NBITS
var app = angular.module("app",[]);

app.controller("Ctrl 1 ",function ($scope) {

$scope.name= "Smith";

$scope.alertName =function(){

alert($scope.name);
};
});

app.directive("testDirective", function(){

return {
restrict: "EA",

scope: {personName:"@pName"},

template: "<div>Your name is: {{personN .

link: function (scope, iElm, iAttrs) {

alert( scope.personN ame);

}
};

});

</script>

</head>

e ="John {{name}}"></div>

</div>

One way textual binding Example explained


Let's understand the one way textual binding. In the previous example the

parent controller is Ctrll. It has a name property which we want to send to the isolated
directive. To do this we will follow 2 steps.
N Benchmark IT Solutions Pvt.Ltd. contacton:910100041s,s91110246s
#101, B-Block, Balaji Towers, Beside Prime Hospital, Near Mytrivanam, Ameerpet, Hyderabad
ANGULAR JS MATERIAL
.\ Snvici: from NBJTS

Stepl: in the scope value we set scope: {personName:"@pName"}. Here the property
personName is the value that will be used within directive.

@pName is the name that is attribute name in the directive element. However the trick is
that pName will become p-name attribute in the directive element.

Step2: Jn the directive element write an attribute with name p-name with value that we
want to be made available to the directive. In our example we w t the name property of
the controller to be prepended with John. We do it as follow st-directive p-name
="John {{name}}"></div>
That's it.. now the property personName is available
Important point to note is that it is 1 way binding.. ng
will affect its value in the directive.

Two way binding


Two-way bindings are prefixed by -

everywhere.
Lets see an example ·binding.html)

<script>

$sco

};

});

app.directive("testDirective", functionQ{

return {
restrict: "EA",

scope: {personName:"=pName"},

template: "<div>Your name is: {{personName}}Change your name witht the input:
<input type='text' ng-model='personName' /></div>",
N Benchmark IT Solutions Pvt.Ltd. contact on: 910100041s, 8911102468
#101, B-Block, Balaji Towers, Beside Prime Hospital, Near Mytrivanam, Ameerpet, Hyderabad
I !

ANGULAR JS MATERIAL
/\ Snvice from NBITS
replace:true,
}:

')·
J '

</script>
</head>
<body ng-app = "app">
<div ng-controller="Ctrll">
<h2 ng-click="alertName()">Hi {{name}}, Click to alert yo
<div test-directive p-name ="name"></ div>
</div>

Two way binding example ex ·


Two-way bindings are prefixed by=
for two way bindings.
one way textual binding.

Step 1: in the scope >e:"=pName"}. Here the property


person Name is the valu

. e p-name attribute in the directive element.

rite an attribute with name p-name with value that is in


iv test-directive p-name ="name"></ div>
roperty personName is available within the directive scope.
s that it is 2 way binding. Changing the value of name
in directive will effect its value in parent and vice versa.

Method binding using @


The third type of binding is using@. This binding binds a value, object or a function. This
type of binding returns a function for a text property or object We need to call the
function to access the value.
Let's see the example below (refer to directives/oneway_binding_&.html)

N Benchmark IT Solutions Pvt.Ltd. Contact On: 9701000415, 8977702468


#101, B-Block, Balaji Towers, Beside Prime Hospital, Near Mytrivanam, Ameerpet, Hyderabad
ANGULAR JS MATERIAL
.'\Sen ice from NBITS

<script>
var app = angular.module("app",[]);
app.controller("Ctrl 1 ",function($scope){
$scope.name= "Smith";

$scope.alertName = function(){
alert($scope.name );
};

});

app.directive("testDirective", function(){

return {
restrict: "EA",
scope: {personName:"&pName"},
template: "<div> Your name is: {{per ·eplace:true,

};

});

</script>
</head>

<h2 , Click to alert your name</h2>

</div>

Understanding the Method Inheriting example


As you can see in the example we exactly follow the same steps. Just one difference. While
referring a method in directive as attribute we refer like this
<div test-directive bind-alert= "alertName()"></div>

Here bind-alert binds to alertName of the parent scope.

N Benchmark IT Solutions Pvt.Ltd. Contact0n:9701000415,8977702468


#101, B-Block, Balaji Towers, Beside Prime Hospital, Near Mytrivanam, Ameerpet, Hyderabad
ANGULAR JS MATERIAL
·\ Sen in· frnm NBITS

Understanding the example


Let's understand the example. again we have followed the same steps as before. Note that
in ODO( directive definition object) we write as

scope: {personName:"&pName"}, .. Here personName is the function that returns the


value.

Note that the binding is obviously one way not two way.

This way we can also inherit functions from parent scop,~~ 4ft~tk';::.now try to inherit a
function using this technique. .'i:
I'diL.c·
'.:';;:

Method binding for isolate scope


Lets understand with an example how we
code below(refer to directives/oneway_

<script>

app.controller("Ctrll ",fun

alert($scope.

};

});

return {

restrict: "EA",

scope: {sayName:"&bindAlert"},

template: "<button ng-click ='sayName()'>Click Here</button>", replace:true,


};

});

</script>

N Benchmark IT Solutions Pvt.Ltd. Contact0n:9701000415,897770Z468


#101, B-Block, Balaji Towers, Beside Prime Hospital, Near Mytrivanam, Ameerpet, Hyderabad
ANGULAR JS MATERIAL
A SnYicc frnm NI3 ITS

</head>
<body ng-app = "app">
<div ng-controller="Ctrll ">
<h2 ng-click="alertName()">Hi {{name}}, Click to alert your name</h2>
<div test-directive bind-alert= "alertName()"></div>

</div>
</body>

Understanding the Method Inheriting ex


As you can see in the example we exactly follow t ce. While
referring a method in directive as attribute we
<div test-directive bind-alert= "alertNam

Simple Binding
Now we have underst of parent in three ways in our
isolate directive scop
ent names in directive scope and
e =,@or&.
e concept(refer to
.html)

ction($scope){

$scope.age= 28;
$scope.alertName =function(){
alert($scope.name);
};

});
app.directive("testDirective", function(){
N Benchmark IT Solutions Pvt.Ltd. Contact0n:9701000415,8977702468
#101, B-Block, Balaji Towers, Beside Prime Hospital, Near Mytrivanam, Ameerpet, Hyderabad
ANGULAR JS MATERIAL
A Scn·ice t'n>m \BITS

return {
restrict: "EA", scope: { sayName:"&", personAge:"=", personName: "@"

},

template: "<div><h4>The age is {{personAge}} and name is


{{personName}}</h4><button ng-click =
'sayName()'>Click Here to view age</button> <br>MOdify Age: <input type= 'text' ng-
model =
'personAge'><br>Modify Name:<input ng-model = 'personN </div>", replace:true,
};

});

</script>
</head>
<body ng-app = "app">
<div ng-controller="Ctrl 1 ">

<div test-directive son-age ="age" person-name = "John


{{name}}"></div>

</div>

rs to attach data or functions within their scope. We just


rty to the DDO with the function that we want to be our

angular.module('app', rn
.directive('testDirective', function() {
restrict: 'E', controller:

function($scope, $element, $attrs, $transclude) {

//The controller logic goes here

N Benchmark IT Solutions Pvt.Ltd. Contact On: 9701000415, 8977702468


#101, B-Block, Balaji Towers, Beside Prime Hospital, Near Mytrivanam, Ameerpet, Hyderabad
ANGULAR JS MATERIAL
A Service from NBITS

})

Note that we can inject the Angular injectors here like $scope,$element,$attrs and
$transclude.
Here $element represents the element reference of the directive.
$attrs contains the attributes object for the current element.
$transclude is the function to modify the DOM and play with the content within the
directive if we need.
Jn the coming section we will be seeing all of these in our exa

Controller example for directive


This example shows how to use the controller w· r to what
we have used in our controllers example earl"

directive (in case of class or attribute


directive attrl = "attr" attr2 = "attr
Next note that within the directive we ha
We have placed them to
controller. Within our co
that prints the attrib ,
in the directive

Understanding the $transclude function


The $transclude function is normally not required as angular itself takes care of
transclusion. However in scenarios if we want to append some html or modify html, we
can make use of the $transclude function.

Below is the snippet showing the use of $transclude function. Note that we can pass
params amongst which is the first param here with the name clone. This parameter
N Benchmark IT Solutions Pvt.Ltd. Contact On: 9701000415, 8977702468
#101, 8-Block, Balaji Towers, Beside Prime Hospital, Near Mytrivanam, Ameerpet, Hyderabad
ANGULAR JS MATERIAL
A Service from NBITS

contains reference to the transcluded element that contains the html within the directive
element.

$transclude(function( clone){
//this is the reference to the cloned element console.Jog( clone);
//this will printtext inside the directive console.Jog( clone.text());
var a= angular.element('<div>');
a.attr(' class',' divclass');
a.text("i am created using transclude function");
$element.append( a);
})

$transdude function ex
In the example below s as divclass using the
$transclude function.
<script>

rest
g inside the directive</h4></div>", replace:true,

e, $element, $attrs, $transclude){


$transclude(function(clone){
//this is the reference to the cloned element console.Jog( clone);
//this will print text inside the directive console.log(clone.text());
var a= angular.element('<div>');
a.attr('class','divclass');
a.text("i am created using transclude function");

N Benchmark IT Solutions Pvt.Ltd. Contact0n:9701000415,8977702468


#101, B-Block, Balaji Towers, Beside Prime Hospital, Near Mytrivanam, Ameerpet, Hyderabad
ANGULAR JS MATERIAL
A Service from NBITS
$element.append( a);
})

};

});

</script>
</head>
<body ng-app ="app">
<div test-directive attrl = "attr" attr2 = "attr2">1 am to be
</body>

Using controllerAs for control

We have another option in DDO to crea


Though its v simple concep ul and very pful. Using controllers as
option, we no longer nee our controller. We can simply use this
current controller ins
g to cess any property or function within
g defined in the controller as option in the
directive.
rective with a controller that has a controller
wit ction in it. Note that instead of using $scope, we have
this to attach them.

$transclude function example


In the example below we are adding a new div with class as divclass using the
$transclude function.
<script>
var app =angular.module("app",[]);
app.directive("testDirective", function(){

N Benchmark IT Solutions Pvt.Ltd. Contact0n:9701000415,8977702468


#101, B-Block, Balaji Towers, Beside Prime Hospital, Near Mytrivanam, Ameerpet, Hyderabad
A~GULAR JS MATERIAL
A Service from NBITS
return {
restrict: "EA",

template: "<div><h4>1 am heading inside the directive</h4></div>", replace:true,


transclude:true,

controller:function($scope, $element, $attrs, $transclude){


$transclude(function( clone){
//this is the reference to the cloned element console.log( clone);
//this will print text inside the directive console.log( clone.t
var a= angular.element('<div>');
a.attr(' class',' div class');

a.text("i am created using transclude function"


$element.append( a);

})
}
};

});

</script>
</head>

Using controllerAs for controllers


We have another option in DDO to create an alias of a controller reference.
Though its v simple concept, yets its very powerful and very helpful. Using controllers as
option, we no longer need to use the $scope within our controller. We can simply use the
this current controller instance.
The important point is that when we are trying to access any property or function within
the html, we can use the reference as the string defined in the controllerAs option in the
directive.
N Benchmark IT Solutions Pvt.Ltd. Contact0n:9701000415,8977702468
#101, B-Block, Balaji Towers, Beside Prime Hospital, Near Mytrivanam, Ameerpet, Hyderabad
ANGULAR JS MATERIAL
.·\ ScrYicc from NBITS

In the next example we have created a directive with a controller that has a controller
with 2 v;iriablcs and one function within it. Note that instead of using $scope, we have
used controller current instance this to attach them.

Using controllerAs example


Example demonstration use of controllerAs option for a directive.
<script>
var app = angula1~module("app",O);
app.directive("testDirective", function(){

return {
restrict: "EA",
template: "<div>Application Name is {{co
inside the directive</h4><button ng-click
me</button></div>",

controller:function(){
this.appName = "Ecom od Morning"; this.greet=
function(){ alert(thi

}
}
};

});

</script>
</head>

<div test-directive attrl ="attr" attr2 ="attr2">1 am to be cloned</div>


</body>

Using external controller within a directive


We can also use external controller defined within the application. Thus controllers can
be reused within the directives. We just need to specify the controller name within the

N Benchmark IT Solutions Pvt.Ltd. Contact0n:9701000415,8977702468


#101, B-Block, Balaji Towers, Beside Prime Hospital, Near Mytrivanam, Ameerpet, Hyderabad
ANGULAR JS MATERIAL
:\ Sen ice from NBITS

directive. Note that the name of the controller is a string so we have to keep within single
or double quotes.

Lets see the next example. You can see that we have defined the controller Ctrll outside
the directive, yet we are able to use the controller functions and properties within our
directive.
Lets see the example in the next slide demonstrating this

Using controllerAs example


,-'
Example demonstration use of external controlleJz"Jro

<script>
var app = angular.module("app",[]);
a pp.controller(" Ctrl 1 ",function($sc
$scope.name= "Smith";
$scope.age= 28;
$scope.alertName = fu

};
});

app.

template: "<div>< heading inside the directive</h4><button ng-click =


'alertName()'>CLick e</button></div>", replace:true,
controller:'Ctrll'
};

});

</script>

</head>
<body ng-app = "app">
N Benchmark IT Solutions Pvt.Ltd. Contact0n:9701000415,8977702468
#101, 8-Block, Balaji Towers, Beside Prime Hospital, Near Mytrivanam, Ameerpet, Hyderabad
ANGULAR JS MATERIAL
A Scnil'l' t'rnm NBITS
<h2>Hi Name is :{{name}} and age is {{age}}</h2>
<div test-directive></ div>
</body>

Using require for directives

One directive can use controller of other directive. To do it ;n~d to use the require
'<'o'i_,~.;

property in the ODO and set its value to the directive whos troller we want to use.

In the next slide we have created 3 directives with the


name product Collection. The two other d'
based directives. The directive produ C
controller. We will be using this func ·

amely brush and cream as attributes to


re added to the items list of main
both the directives brush and
cces the controller of productCollection
we use require, automatically the fourth
e mention in require property.

Using require
This is the main pro ct collection directive. The next slide will continue this example.
<script>
var app =angular.module("app",[]); app.directive("productCollection", function(){ return
{
restrict: "E",
template: "<div><h4>This is the basket</h4><button ng-click =
'pCRef.totaiAmount()'>Show Total</button><button ng-click =
'pCRef.showltemsN o() '>Items Count</button></ div>", replace:true,
N Benchmark IT Solutions Pvt.Ltd. contact on: 910100041s, 8911102468
#101, B-Block, Balaji Towers, Beside Prime Hospital, Near Mytrivanam, Ameerpet, Hyderabad
ANGULAR JS MATERIAL
A Sen 1ec i'rnrn NRITS
controllerAs:"pCRef',

controller:function ($scope, $element, $attrs, $transclude ){


this.itemsCount = O; this.items=[]; this.msg ="test";
this.showltemsNo =function(){ console.log('in') alert(this.items.length);

}
this.totalAmount = function(){

var totalAmount = O;
for( var i = O;i<this.items.length;i++ ){
totalAmount+=this.items[i].price;

}
alert(totalAmount);

}
this.addltem = function(item){
this.items.push(item);
}

}
};
});

ample in previous slide. Here we have written the two directives


that will require the main directive. app.directive("brush",function(){

return {
require:"productCollection;', link:function(scope, element, attrs,pCCtrl ){

console.log(pCCtrl);
pCCtrl.addltem({name:'brush',price:12});

N Benchmark IT Solutions Pvt.Ltd. contacton:910100041s,s9111oz46s


#101, B-Block, Balaji Towers, Beside Prime Hospital, Near Mytrivanam, Ameerpet, Hyderabad
ANGULAR JS MATERIAL
A Service from NBITS

})

app.directive("cream",function(){ return { require:"productCollection",


link:function(scope, element, attrs,pCCtrl ){
pCCtrl.addltem ({name:' cream ',price:30});

})

</script>
</head>
<body ng-app ="app">

<product-collection

</body>

on. We can put the contents between the


nsclude property. Note that we used the ng-
thin the directive view. Angular gives us power
ction b hich we can put the contents inside directive tags
de function we get a lot of flexibility to decide where and
tent. Note that we pass a function to the $transclude

<script>
var app =angular.module("app",[]);
app.directive("testDirective", function(){
return {
restrict: "EA",
template: "<div><h4>1 am heading inside the directive</h4></div>", replace:true,
N Benchmark IT Solutions Pvt.Ltd. contacton:910100041s,s91110246s
#101, 8-Block, Balaji Towers, Beside Prime Hospital, Near Mytrivanam, Ameerpet, Hyderabad
~-------------~-------- ---------------- ·--------~

ANGULAR JS MATERIAL
A Service !"rnrn '\JillTS

transclude:true,

controller:function($scope, $element, $attrs, $transclude){

$transclude(function( clone){

//this will print text inside the directive var a= angular.element('<div>');


a.attr(' class',' divclass ');

a.text("i am created using transclude function");

$element.append( a);

})
}
};

});

</script>

</head>
<body ng-app = "app">

t server communication.
to and fro to server.

service, learn about setting headers, Modifying

learn eve etter and advanced way using the Restful built in API in
better and recommended way of developing the REST APL

$http service

The full $http API

$http({

method: string, url: string, params: object,

data: string or object,


N Benchmark IT Solutions Pvt.Ltd. Contact On: 9701000415, 8977702468
#101, B-Block, Balaji Towers, Beside Prime Hospital, Near Mytrivanam, Ameerpet, Hyderabad
ANGULAR JS MATERIAL
A Service from NBITS

headers: object,
transform Request: function transform( data, headersGetter) or an array of functions,

transform Response: function transform( dClta, headersGetter)


or
an array of functions,
cache: boolean or Cache object, timeout: number,
withCredentials: boolean
});

Understanding parameters in
Method: The method represents the
GET, POST, and DELETE etc.

URL: the Uri parameter re erver. params: The parameters to send


with the request.
a. Headers: any additional headers

e request transformResponse: the function


an parameter for caching or custom caching

t the number of milliseconds after which request

this parameter to true will also send the session id with the
request.

Simple $http request example


Refer to scm/http/http_get.html. Note that the

<script type="text/javascript">
var myModule = angular.module('myModule', O);
myModule.controller('MyCtrl', function ($scope,$http,$sce) {
N Benchmark IT Solutions Pvt.Ltd. contact on: 910100041s, 8911102468
#101, B-Block, Balaji Towers, Beside Prime Hospital, Near Mytrivanam, Ameerpet, Hyderabad
ANGULAR JS MATERIAL
A Service from NBITS

$scope.todos = [);
$scope.errorMsg = null;
$scope.click= function() {
$http.get('slim/todos', {params: {id: '5'}
}).success(function(data, status, headers, config) {
$scope.todos = data;
}).error(function( data, status, headers, con fig) {
$scope.errorMsg = $sce.trustAsHtml(data);
});

};

});

</script>
</head>
<body>
<div ng-app="myModule"

</div>

</div>
</div>

Understanding $http request example


The example makes a get request to the server which returns an array of to-do
Items. We bind it tong-repeat.As the data comes from server, the data changes.
Note that the errorMsg contains the error if any happens. The data parameter of the error
functions contains the response from the server.

N Benchmark IT Solutions Pvt.Ltd. Contact0n:9701000415,8977702468


#101, B-Block, Balaji Towers, Beside Prime Hospital, Near Mytrivanam, Ameerpet, Hyderabad
1- ANGULAR JS MAlERIAL
\ Service from NBITS
Try changing the url and you will see the error message from the server shown in the
view.
Note that If we try to show the error message directly It will show the html code returned
from the server. This is a security feature to avoid xss attack. To
show an html that we trust we have to pass it to the trustAsHtml function of
$see service like this $scope.errorMsg = $sce.trustAsHtml(data);
The returned valued can then be bound to the html using the ng-bing-html directive as
shown in the html like this <div ng-bind-html = "errorMsg"></di¥?

$http function shortcuts

Angular provides a list of functions which aJ~~~~ho·


requests.

$http.put: put re
$http.delete :

$htt

$http.get('/serverUr .success(successCallback);
$http.post('/ serverUrl ', data).success(successCallback);

Caching the server Response

TO implement caching we can set the caching parameter value to be true.

N Benchmark IT Solutions Pvt.Ltd. Contact0n:9701000415,8977702468


#101, B-Block, Balaji Towers, Beside Prime Hospital, Near Mytrivanam, Ameerpet, Hyderabad
A~GULAR JS MATERIAL
.'\ Service from NBITS

$http.get('http://server/api', {
cache: true
}).success(function() {//success handling});

Note that for multiple simultaneous requests for


Same URL, only one request is made to the server and the response is used for all the
requests. Even if the response is being served from the cache, It is still
Asynchronous in nature means our code will behave as it
request.

Request and response Transfor


Request and response transformation is
made by angular.
Why do we need to modify the req

We may also modify the narios, ex: if the server returns JSON
string, we might want · doing our self every time.

nse transformations too

est object contains an object, angular serializes it

If an XSRF prefix is detected in the response, angular strips it.


If a )SON response is detected, angular deserializes it using a JSON parser.

Custom transformations
If we don't want some of the transformations, or to add our O\.\'n, then we can pass in
functions as part of the config.
N Benchmark IT Solutions Pvt.Ltd. Contact0n:9701000415,8977702468
#101, B-Block, Balaji Towers, Beside Prime Hospital, Near Mytrivanam, Ameerpet, Hyderabad
ANGULAR JS MATERIAL
i\ SL'n IL'L' r1nm NBITS
We can transform a request or a response at the request/response phase using the
transform Request and transform Response property of the object that we pass to the
$http function.

Note that this method is good if we want to modify a single request/response. If we want
to modify the request/response globally, we need to do it in the config function of the
module. Lets understand this in the next section.

Custom response transformation example


Refer to scm/http/responsetransformation.html

<script type="text/javascript">
var myModule = angular.module('myModule', []
myModule.config(function($httpProvider){

$httpProvider.defaults.headers.common.t

$httpProvider.defaults.transformRes
return {responseData:angular.from so w()};

})

$scope.todos -

atus, headers, config) {

$scope.errorMsg = $
});

};

});

</script></head>

<body><div ng-app="myModule"

<div ng-controller="MyCtrl">

N Benchmark IT Solutions Pvt.Ltd. Contact0n:9701000415,8977702468


#101, 8-Block, Balaji Towers, Beside Prime Hospital, Near Mytrivanam, Ameerpet, Hyderabad
ANGULAR JS MATERIAL
:\ Snvicc l'rnm NBITS
<div ng-repeat = "todo in todos">
status is: {{todo.status}} and description is: {{toqo.description}}</div>
<div ng-bind-html = "errorMsg"></div><button ng-click="click()">Show
Number</button>
</div></ div>

Custom transformation example explained

IN the previous example we have transformed the respon


function of the module. We have added a token valu
console you can see the token value as header.

Also we have modified the response th rom the ser


response received was a json string, · ct, added a new todos object
to the array and returned it.

Handling Restf
$
th server but to make REST requests with
,POST, UPDJ\fE and DELETE. However we

use the ngResource Module.


The ngResource ule provides a well builtAPI to handle rest based calls. To use it we
have to download t ular-resource.js file.
· Next while declaring he app we have to include ngResource as dependency.

Ex: Vclr app = angular.module('myApp',[ngResource]);

Using the ngResource API


N Benchmark IT Solutions Pvt.Ltd. Contact0n:9701000415,8977702468
#101, B-Block, Balaji Towers, Beside Prime Hospital, Near Mytrivanam, Ameerpet, Hyderabad
ANGULAR JS MATERIAL
A Sen in· frnm NBITS
To create a resource object we need use the $resource service
Below is the sytax
var resourceOb = $resource('api/comments/:id');
Here the :id represents the dynamic parameter id for the REST request
This resource object consists of a set of functions to communcate with the REST AP!.
Following are the functions availble on the resource object
'get': {method:'GET'},
'save': {method:'POST'},
'query': {method:'GET', isArray:true},
'remove': {method:'DELETE'},
'delete': {method:'DELETE'}

To calll a get method we just need to w "te


Var resultOb= Entry.get({id:12},fun

});

in the next section.

Refer to scm/rest Test_example.html


<script>
var app =angular.module('myApp',('ngResource']);
app.factory('Entry', function($resource) {
return $resource('api/ comments/:id ');
});
app.controller('test',function($scope, Entry) {
= null, $scope.singleComment =null,$scope.id = 12;
$scope.entries
N Benchmark IT Solutions Pvt.Ltd. contact on: 910100041s, 8911102468
#101, B-Block, Balaji Towers, Beside Prime Hospital, Near Mytrivanam, Ameerpet, Hyderabad
----------- ---------~

ANGULAR JS MATERIAL
A Sen in' fr<J111 0: !\ITS

$scope.fetch = function(id){

$scope.singleComrnent = Entry.get( {id:$scope.id} );

$scope.deleteComrnent = function(){ Entry.delete( {id:$scope.id},function (){


alert("Comment delete request sent to server");

}) }
$scope.postBack = function(){ Entry.save($scope.singleComment,function(){
alert("Modified comment successfully posted back to

}) }

$scope.fetchAll =function(){

$scope.entries= Entry.query();

} });

</script></head><body> _

<div ng-controller ="test">

<div id= "all-comments"

<div ng-repeat ="en comment with id {{entry.id}} and


fulll description a

{{entry.descri

><button ng-click = "fetch()">Get

<div id= "single-c e t"> The comment with id {{id}} has status
{{singleComment.sta and full descriptions as

{{singleComment.fulldescription}}</div> MOdify the comment below

<input type = "text" ng-model = "singleComment.status"><input type = "text" ng-


model = "singleComrnent.fulldescription">

<button ng-click = "postBack()"> Post back </button></ div>

N Benchmark IT Solutions Pvt.Ltd. Contact0n:9701000415,8977702468


#101, B-Block, Balaji Towers, Beside Prime Hospital, Near Mytrivanam, Ameerpet, Hyderabad
ANGULAR JS MATERIAL
A Service from NBITS

Using the returned restful object


Note that When data is returned from the server, the returned object is also an instance
of the resource class.
The actions save, remove and delete are available on this object as methods with $
prefix. This technique allows us to easily perform CRUD operations on the returned
object itself. The previous example can also be rewritten like this. (refer to
scm/rest/restexample.html)
<script>
var app = angular.module('myApp',['ngResource']);
app.factory('Entry', function ($resource) {

return $resource('api/ comments/ :id');


});
app.controller('test',function($scope, Entr
$scope.entries= null, $scope.singleCo
$scope.fetch= function(id){

$scope.entries = Ent

}
});

</script>

Restful example explained

N Benchmark IT Solutions Pvt.Ltd. Contact0n:9701000415,8977702468


#101, B-Block, Balaji Towers, Beside Prime Hospital, Near Mytrivanam, Ameerpet, Hyderabad
ANGULAR JS MATERIAL
A Service from NBJTS

IN the previous example we have tried to use the REST API to make get, post and delete
requests.
Note that we have used the factory singleton object to retrieve the resource object.
To fetch all the comments from the API, we have use the query function which returns all
the comments. It's important to understand that we don't need to bind the result in the
success call back. The data is automatically retrieved and reflected in the template as it is
returned. See the snippet

$scope.entries= Entry.query();

Here the return value is directly bound to the$ the value


in the success call-back. This is taken care by

Caching in Angularjs ·

The $cacheFactory
acheFactory('AppCachelD'); Here

the $cacheFactory where we can speciify the

che in this case) we can store and retrieve the cache data.

Using cache o
The cache object has many methods to store,retrieve and get information about the
caches.
Following are the methods

info() :This method returns ID, size and options of the cache object.
put():This method stores the data in the cache, The first parameter is the key and second
is the data to store.appCache.put('name','sumit'); appCache.put('hobby','coding');
N Benchmark IT Solutions Pvt.Ltd. contact on: 910100041s, 8911102468
#101, B-Block, Balaji Towers, Beside Prime Hospital, Near Mytrivanam, Ameerpet, Hyderabad
ANGULAR JS MATERIAL
A Service from NBlTS

get(): get methods retrieves the data from the cache for the given cache id.
appCache.get('name');
remove(): This function removes a key-value pciir from the cache, if it's found.

If not found, it returns undefined .appCache.remove('name');


removeAll(): This function resets the cache and removes all cached values.
appcache.removeAll()
destroy() This method removes all references of the current cache from the
$cacheFactory cache registry. le appCache.destroy()

$http caching
The $http service creates a cache with the ID st to use
this default cache object we have to pass a c
Ex
$http({
method: 'GET',

});

e object. But if needed we can retrieve it using

//To Delete the cache entry for the previous request


cache.remove('http://acadgild.com/api/comments.json');

//TO remove the entire cache cache.removeAll();

Using custom cache for $http

N Benchmark IT Solutions Pvt.Ltd. Contact0n:9701000415,8977702468


#101, B-Block, Balaji Towers, Beside Prime Hospital, Near Mytrivanam, Ameerpet, Hyderabad
ANGUL\R JS MATERIAL
A Service from NBITS

Note that we can use our own custom cache for $http too.
Instead of passing a Boolean true for $http, we can pass the instance of the cache.
Below is the example

var appCache = $cacheFactory.get('AppCache!D');

$http({
method: 'GET',
url: '/api/comments.json', cache: appCache
});

Configuring cache setting

We can also configure the set ·

angular.module(' Co
.config(functio

});

For AngularJsApplications we need 2 types of testing


1) Unit Testing: Unit testing is for testing the code. Its similar to the way we test server
side application ..ie }unit.
2) End to End testing: Unit testing is not enough. We also need to know how the
application behaves to the user interactions in the browser. For this we need to simulate
user interactions at the browser.

N Benchmark IT Solutions Pvt.Ltd. Contact0n:9701000415,8977702468


#101, B-Block, Balaji Towers, Beside Prime Hospital, Near Mytrivanam, Ameerpet, Hyderabad
~-----------~- ----------------

ANGULAR JS MATERIAL
. \ Sl'n1cc lrnm NBITS

For unit testing JavaScript applications we can use jasmine. For End to End testing we can
use Protractor.

we will be using protractor testing framework built over selenium and jasmine.

End to End Testing vs Unit testing

We now know that there are 2 types of testing. Which testing we use? Unit or End
To End?

The answer is that we should use both to make a robust ap


Unit testing is good for testing controllers wher
changes in templates and view.Agood applicatio testing.

List of Frameworks needed to comple again have a


frameworks we need for testing Jas work for unit testing
Karma:Karma is a task runner for unit the test and provided
a lot more features to make te ·

Protractor:Protractor is
e2e tests for angular.

Jasmine

elopment unit testing framework for testing

ine from be downloaded from http://jasmine.github.io/

lied using npm(node package manager).Use the command in


npm install -g jasmine

Alternatively you can download the standalone version of jasmine.. Coz its just

JavaScript!
We won't be going deep into testing with jasmine because we will be using protractor for
testing.

N Benchmark IT Solutions Pvt.Ltd. Contact0n:9701000415,8977702468


#101, B-Block, Balaji Towers, Beside Prime Hospital, Near Mytrivanam, Ameerpet, Hyderabad
ANGULAR JS MATERIAL
~\ Sen 1l'l' t'rum NBITS

Jasmine spec

An expectation in Jasmine is an assertion that is either true or false. A spec is a collection


of exceptions

A spec with all expectations as true is a passing spec.


If a spec has one or more false expectations, it is a failing spec. Ex of a spec
it("and has a positive case", function() {
var a= 5,b=S;
expect( a).toBe(b );

}); •

What is a Suite
A suite is a collection of specs.

Ex of a suite

it("and has a

exp
1)·
J '

});

Setup and tear down for tests

Following are global functions namely beforeEach, afterEach, beforeAll, and afterAll.
The before each function is called once before each spec in the describe is run. The after
each function is called once after each spec.
They can be used to reset variabies before a spec.

N Benchmark IT Solutions Pvt.Ltd. Contact0n:9701000415,8977702468


#101, B-Block, Balaji Towers, Beside Prime Hospital, Near Mytrivanam, Ameerpet, Hyderabad
ANGULAR JS MATERIAL
A SLT\'JL'l' lrnm NBITS

The beforeAll function is called only once before all the specs in a describe are run.

The afterAll function is called after all specs finish.

Setting up and creating tests

We will be downloading the standalone version of jasmine. After downloading we have


the following folders

l)lib: The lib folder contains the libraries for jasmine

Z)spec: spec is the folder where will be keeping our te


3)src: the folder where our code to be tested will

We also have a file called specrunner.htmr


run our tests.

be tested, the unit test and the

As·

and other multiplies the numbers will be

Below is the code to

functionAddTwoNumbers(a,b) {

return a + b; //Function to return addition of two numbers a and b.

N Benchmark IT Solutions Pvt.Ltd. Contact0n:9701000415,8977702468


#101, B-Block, Balaji Towers, Beside Prime Hospital, Near Mytrivanam, Ameerpet, Hyderabad
ANGULAR JS MATERIAL
function MultiplyTwoNumbers(a,b) {

return a* b; //Function to return product of two numbers a and b.

Code for unit test


The code is kept as jasminetesting/spec/unittest.js Below is the code
To test the code just run the specrunner.html file.

describe("Testing Two Numbers", function() {

var a= 4,b = 3;
beforeEach(function() {
console.log("Setting up ");

a= 4,b =3;
});
afterEach(function() {

a=O,b=O;
});

exp
});

ers( a,b )).toEqual(p);

});
it(" Compare Numbers to be Greater Than", function() {

expect(a).toBeGreaterThan(b);

});

});

N Benchmark IT Solutions Pvt.Ltd. Contact0n:9701000415,8977702468


#101, 8-Block, Balaji Towers, Beside Prime Hospital, Near Mytrivanam, Ameerpet, Hyderabad
ANGULAR JS MATERIAL
A Service l'rom Nl:llTS

Setting up unit testing for Angularfs


To start with we need to install karma and karma cli on the system.
This can be done either using npm(node package manager).
You just need to run npm install -g karma and npm install -g karma-di. The above two
commands install karma on the machine.
Once done we can now start setting up our environment.
Lets create a directory called project_one. inside this directory
directories namely scripts, test,. Inside test directory we will
be creating 2 directories namely e2e and unit. e2e will co
will contain unit tests.
Create a file called codetotest.js and keep ·Create a
codetotestSpec.js file and keep inside test/unit
Use the command line and go to project_o
Inside the directory fire the commrn
linux
We use this command to create a karma
asks for some options and f
configuration file. The
As soon as we run this ill ask you a few options. Lets look
at the options i

Ka

Setting the unit testing framework. The default is jasmine. We can


works like mocha or chai. Note that use tab key to select other
choices

Which testing framework do you want to use ?


Press tab to list possible options. Enter to move to the next question.
>jasmine

N Benchmark IT Solutions Pvt.Ltd. Contact On: 9701000415, 8977702468


#101, B-Block, Balaji Towers, Beside Prime Hospital, Near Mytrivanam, Ameerpet, Hyderabad
ANGULAR JS MATERIAL
A Servin~ from NB ITS

If you are using require)s then say yes to the next option. Default is no

Do you want to use Require.js ? This will add Require.js plugin.


Press tab to list possible options. Enter to move to the next question.
>no

We can next select the browsers to choose. We will use chro

--------------------------------------------------------------- Do you
automatically ?
Press tab to list possible options. Enter empty n.
>Chrome

Next option asks for the locat' tests to be run. see the
answer highlighted in blu nter muliple options using an enter.ie
after entering one opti nter without entering any option it
moves to the next q
--- What is the location of your source and
test files?
est/** f*Spec.js". Enter empty string to move

> scriptsf*.js
> test/unitf*Spec.js
>

Next option asks for any pattern of files to be excluded. For now press enter without
entering any option.

N Benchmark IT Solutions Pvt.Ltd. Contact0n:9701000415,8977702468


#101, 8-Block, Balaji Towers, Beside Prime Hospital, Near Mytrivanam, Ameerpet, Hyderabad
I
ANGULAR JS MATERIAL
A Service from NBITS

Should any of the files included by the previous patterns be excluded ? You can use glob
patterns, eg. "**/*.swp ".

Enter empty string to move to the next question.

Next karma asks if we want to detect any changes in code and retest it. We will use the
default yes and press enter.

Do you want Karma to watch all the files and run the tests o
possible options.
>yes
After this we can see the message which says that rated.

Testing the code using karma


Remember in the last exercise we tested us·
using karma.
To test, lets get the code from fold .js and keep it replace
it with the file project_one/scripts/codet
Next we will open the fi t/unit/codetotestSpec.js and copy the
contents of jasminetes ·
rote earlier using karma.
e the command karma start karma.conf.js

en the browser and run the tests for us. After the tests

expect(AddTwoNum
To expect(AddTwoNumbers(a,b)).toEqual(l 7);

Karma will automatically detect the change and run the test for you again.

Setting up protractor for End to End testing

N Benchmark IT Solutions Pvt.Ltd. Contact On: 9701000415, 8977702468


#101, B-Block, Balaji Towers, Beside Prime Hospital, Near Mytrivanam, Ameerpet, Hyderabad
ANGULAR JS MATERIAL
A Service from NBITS

Lets now install protractor.

We can install protractor using the command npm install -g protractor


After that update the webdriver by
npm install webdriver-manager update
This will install protractor in your system

In the next section we will set up a simple testing project with protractor.

Setting up protractor for testing


Lets set up a small project and test with pr
,,.Ci;eate a folder named pr9ject_e2e.
src where we will keep our sourc

The code just adds 2 v ut box and displays the output on


clicking the add butto to testing/project_e2e/src/ng-
model_ example.ht

</script>

[]);

$scope.result = parselnt($scope.a)+parselnt($scope.b );
};

});

</script>

</head>
<body ng-app="myModule">

N Benchmark IT Solutions Pvt.Ltd. Contact On: 9701000415, 8977702468


#101, B-Block, Balaji Towers, Beside Prime Hospital, Near Mytrivanam, Ameerpet, Hyderabad
ANGULAR JS MATERIAL
.'\ Sn\'icc from NBITS
<div>
<div ng-controller="MyCtrl">
<p>Firstname: <input type="text" ng-model="<i"></p>
<p>Lastname: <input type="text" ng-modei="b"></p>
<p>{ {result}}</p>
<button ng-click="click()">ShowName</button>

</div>
</div>

Setting up protractor for testing


To run the protractor we need to create a co,n
protractor. Create a file with the name con > .

Refer to testing/project_e2e/config."
seleniumAddress:'http://localhost.
capabilities:{

},

}
}

capabilities propert or which browsers we want to run the test.


specs property is an array that consists of the file to be run by the protractor for testing
jasmineNodeOpts represents options that we can pass to the jasmine node.

Running the test

N Benchmark IT Solutions Pvt.Ltd. Contact0n:9701000415,8977702468


#101, 8-Block, Balaji Towers, Beside Prime Hospital, Near Mytrivanam, Ameerpet, Hyderabad
-----~----------------------------------

ANGULAR JS MATERIAL
A Snvicc from NBITS
To run the test first we need to start the selenium server. We will use the command web
driver-manager start to start the server.

After the server is started, we will open a new terminal. Go to testing/project_e2e/


directory. Then we fire the command protractor config.js

This command will load the config.js in the protractor and start the testing.

You will the chrome browser opened, values entered automatically and tested by the
framework.

N Benchmark IT Solutions Pvt.Ltd. Contact On: 9701000415, 8977702468


#101, B-Block, Balaji Towers, Beside Prime Hospital, Near Mytrivanam, Ameerpet, Hyderabad

Potrebbero piacerti anche