Angular Bits
Angular Bits
...A.
. ~
N ••
B: ·1<·T S
•••••H•·{.//\;
1
./;'•: ,.· .·. . ~
SAP
•HANA
•BODS
• BOBI
•BW
Angular JS • BPC
• ABAP
Tonics
1. HTML
2. HTML5
3. css
4. CSS3
5. JavaScri
6. Advan
7.
8.
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.
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
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.
• 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
<html>
<body>
<hl> Hi .. I am a heading</hl>
</body>
</html>
1. Block level tags: Block level tags add a line break for the content
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.
' ' i .. :
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
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.
<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
</head>
<body>
<hr/>
</body>
</html>
Creating Tables
HTML table can be considered as group of rows where each of them contains a group of
cells.
Table Example
<table>
<tr>
</tr>
</table>
Ordered List Tags Example
<OL TYPE="l">
<LI> Item one </LI>
<LI> Item two </LI>
<OL TYPE="I" >
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.
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.
<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
TMLS
What Is HTMLS?
• Successor of HTML 4.01 and XHTML 1.1
• It comes with new tags, features and
HTML Structure
An HTML page first starts with the DOCTYPE declaration
<!DOCTYPE html>
<html>
<head>
</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.
HT
at provide for more data-specific UI elements and native
l of 13 new input types:
Search
url tel
datetime date
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
HTML Geolocation
Geolocation allows your visitors to share their current location. Location are determined
by any of the following:
• 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.
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>
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>
</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.
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.
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):
/ / light green
grd.addColorStop(O, '#8ED600');
/ / dark green
grd.addColorStop(l, '#004COO');
context.fillStyle = grd;
context.fill();
</script
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
• 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)
<video controls>
<source
src="movie.webm"
<source
</video>
<audio>
<source
src="song.mp3" type="audio/mpeg"/>
</audio>
Modernizer
<script
src="modernizr.min.js"
type="text/javascript">
</script>
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.
<html>
<body>
<p> Hi..I am text inside a paragraph</p>
</body>
</html>
Inside CSS code we mention the tag name we want to format and then add the properties
inside curly braces.
Structure of a style
• A property
• A colon
• A value
• A semicolon to separate two or mo
p{font-size:12px; color:red}
Tag Selector
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.
• Clztss selector
• Mixed selectors which are combination of the above three.
ID Selector
#para{
color: red;
font-size: 20px;
}
· 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
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>
</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>
</head>
<body>
<hl>hello</hl>
</body>
</html>
Box Model
·. ·adding is the spacing
the padding. Margin is
surrounding space aroun
margin:<top><top-right><top-bottom><top-left> Similarly: pa
right><top-bottom><top-Ieft> Ex:
hl{
margin: Spx 2px 3px Spx;
}
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
hl{
border: Spx solid red
}
rty removes the element from the document flow and moves them
e float property.
Float property
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.
Clear-fix code
Div, Span
Every element has a default display value depending on what type of element it is.
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.
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
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
max-width
#outer {
max-width: 600px;
margin: 0 auto;
}
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
</div>
.burgerp {
background: brown;
}
p.cheese {
background: yellow;
}
.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 {
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{
RGB Color
.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.
For shade of orange to appear 70% opaque, we would use an RGBa color value of
rgba(255, 102, 0, .7).
ANGULAR JS MATERIAL
A Service from NBITS
.container {
background: rgba(128, 0, 0,.7);
}
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.
div{
font-size: 14px;
}
Relative Length
.main {
width:40%;
}
Relative I.:
Ex
.menu{
font-size: 24px;
width: 3em;
}
Ex
.banner{
font-size: 14px;
width: Sem;
}
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.
Cascading of Styles
body { font-famil
p { color: grey; }
strong { font-size: 14
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.
Specificity!
p.color-red{
color:red;
}
p{
color:green;
}
font. As per the rule, the later style should override the
nt should be red?
Specificity Score
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
}
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
.sidebar{
float:none;
padding-top: 10px;
Understanding CSS3
Successor of CSS2
CSS 3 Gradients
CSS3 can be used to create gradient
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);
}
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);
}
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
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
1 1px
• 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;
/*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)
• 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' · ·
• 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
: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
}
cript
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.
<html>
<head>
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;
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:.
Operators
• 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;}
else { statements; }
else if Statement
Allows you to test for value and executes a particular
block of code.
Syntax:
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.
• The change_exp determines how much has been added or subtracted from the
counter variable.
Syntax:
{ statements; }
Syntax:
{ statements;
while loop
• dition and keeps looping until the
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;
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
• · n called arguments .
•
Scope
"Scope" refers to the variables that are available to a piece of code at a given time.
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';
console.log( foo );
};
Example:
var sayHello =function() {var foo ='
};
Scope
ifferent scopes with different values
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
g,S="button_off.gif"
<head>
<~~~p!>
funs;SlQD. toggle()
Lf!9chJJ!t~J1!~Jwsi.:!>J1!:to
"button_on.gif";}
</script>
</head>
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.
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.
};
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
ANGULAR JS MATERIAL
A Srrviet~ from NBITS
Action Dialog
<script type="text/javascript">
function confirmDelete() {
var answer= confirm("Are you sure you want"
+"to delete this player?");
return answer
}
</script>
</form>
Form Validation
<script>
function validate() {
if (document.getElementByld("name").value.length == 0) {
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()" >
Javas
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.
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
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];
Immediate Function
An immediatefunction is a function t in ed.
function Ftimes() {
var FtimesObj =new Object()
function Ftimes3(x) {
return x * 3
}
function Ftimes4(x) {
Ftimes0bj.Ftimes3 = Ftimes3
Ftimes0bj.Ftimes4 = Ftimes4
return FtimesObj
}
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 );
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
• objectName.property
• objectName["property"]
• objectName [expression]
Enumerable Properties
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
• example: when
Point.prototype
• initially this ob"
• every object s prototype object as its prototype
(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() {}
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
=animal.
Multiple Inheritances
Inheritance is all about copying properties from parent to child prototype, then why
not copy properties from multiple parents.
function multilnheritance() {
}
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
Deep Copy
function deepCopy(p, c) {
c = c 11 {};
for (var index in p) {
ery
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
<head>
</script>
</head>
}Query Syntax ·
The jQuery syntax is tailor made for selecting HTML elements and performing some
action 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
•
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().
JQuerylraversing Parent
<div class="parent">
</div>
</div>
<div class="parent">
<div class=" child">
<span class="subchild"></span>
</div>
</div>
</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>
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.
• $("#target") .before("add da
$('a').click(function( ev) {
$(this).css({background Color: 'orange'});
ev.preventDefault(); });
Event - mouseover
]Query Example of mouseover event that shows a submenu when menu selected:
$('#menu').mouseover(function() {
$('#submenu').show();
});
}Query Forms
ANGULAR JS MATERIAL
\ Ser\ ILL' i'rom NBITS
else {
Do stuff if box is not checked
}
Example
$( document).ready(function
• 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!
• The $.post() method requests data from the server using an HTTP POST request.
• Syntax:
$.post(URL,data,callback);
}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(){
});
}Query Template
}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:
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,
• Application structure
• Managing the co
Angularjs Features
Following are the features which make AngularJs an ideal framework for developing web
applications
1. Providing structure to develop front end web applications, Angularjs has inbuilt
support for modules, controllers, factories, and services to modularize the code
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
AngularJs Expressions are similar to JavaScript expressions that get evaluated within
double curly braces.
Ex: {{1+8}
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}}</
</div>
I
ANGULAR JS MATERIAL
A Service from NBITS
Data 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
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.
First the template which is the uncompiled HTML is compiled on the browser.
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.
•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
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.
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++.
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.
</script>
</head>
<body>
<div ng-app="myModule"
<div ng-controller="MyCtrl">
<p>{{"Name is"+ name+" and loca ·
</div> </div>
Understandin
revious example.
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.
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.
});
</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">
</div>
</div>
Refer to controllerwithfuncti
$sco
name.firstname);
};
});
</script>
</head>
<body>
<div ng-app="myModule"
<div ng-controller="MyCtrl">
<p>{{name.firstname + "" + name.lastname}}</p>
</div>
</div>
Using ng-model
e ng-model directive.
Also see the Ii alue in the text boxes and you can see the
r.module('myModule', []);
});
</script>
<p>{{firstname + 11 11
+ lastname}}</p>
</div>
</div>
Understanding directives
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
ANGULAR JS MATERIAL
A Service from NBITS
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.
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
$rootscope
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">
myM odule.run(function($rootScope )f
$rootScope.appName = "Te
})
});
$scope.lastname =
});
</script>
</head>
<body>
<div ng-app="myModule">
Scopes Hierarchy
controller.
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.
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;
});
$scope.company = "Google";
$scope.modelchild = modelchild;
});
</script></head>
<body>
<div id = "boundry" ng-app="
.C,'t
stname"></p>
</div>
</div>
-controller= "ChildCtrl">
Your hobby is {{modelchild.hobby}} your first name is {{model.firstname}}
</div></ div>
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"
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.
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
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.
Refer to controller_this_inheritance.html
<script type="text/javascript">
});
});
</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}}
Filters
</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.
<script type="text/javascript">
$scope.name = $filte
});
</script>
<bo
</div>
</div>
<script>
angular.module('myModule', 0)
$scope.amount= 1234.565555;
}]);
</script>
</head>
<inp
an id="currency-default">{{amount I currency
</div>
<script>
angular.module('myModule', [])
.controller('NumberController',
$scope.val= 2345.978777899;
}]);
</script>
</head>
r: <input ng-model='val'><br>
Using Date
date to a string based on the requested format. Template format
Note that data can be either an ISO date object or date string or timestamp
Ex:
<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.
Syntax:
<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;
$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
<script>
angular.module('orderByApp', [])
.controller('OrderByController',function($scope) {
$scope.friends =
[{name:'Smith',phone:'SSS-1512', age:20},
});
</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
</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>
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() {
}
});
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">{{
</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>
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'])
angular
.module('module 1 ', ['module2 '])
.config(function () {console.log(" came h
.run(function () {console.I
. angular
fig of module2");})
</s
</div>
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
Routing
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.
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.
}).
ction($scope, $routeParams) {
})
oiler' ,function($scope) {
})
</script>
</head>
<body ng-app="sampleApp">
</body>
})
The following code is fire s above are found. We have loaded the
index page data here.
});
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.
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,' ,
return result;
}
});
$scope.reversename = wordService.reverseWord($scope.name);
})
$scope.capitalizeName =function(){
$scope.reversename = wordService.capitalize($scope.reversename);
});
</script>
</head>
<body ng-app = "serviceExample">
<div ng-controller = "MyCtrl">
<input type= "text" ng-model ="name"> Name in reverse is: {{reversename}}
</div>
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 = "";
capitalize :function(input){
return input.toUpperCase(); }
}
return literalObject;
});
factoryExample.controller('MyCtrl' ,func
$scope.reversename = wordFacto
})
}
});
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());
}
});
</script>
</head>
<body ng-app = "providerExample">
<div ng-controller ="MyCtrl">
<button ng-click = "displayMessage()">Display Message</button>
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.
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>
}
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.
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.
Character
E element <hello
title=Products></hello>
A attribute <div
c class
u:Products></ d
M directive: menu
Products -->
<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',
});
</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.
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.
We wrote a
provided.
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)
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.
<body>
><p> i am a paragraph</p></div>
restrict:'A',
template: '<div> <h3 ng-transclude></h3></div>', transclude: true,
replace: true
};
});
</script>
</body>
Scopes
Three types of scopes available for directives
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
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
};
});
</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>
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.
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.
l."@"
2. "="
<script>
$scope.name= "Smith";
$scope.alertName =function(){
alert($scope.name);
};
});
app.directive("testDirective", function(){
return {
restrict: "EA",
scope: {personName:"@pName"},
}
};
});
</script>
</head>
e ="John {{name}}"></div>
</div>
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.
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>
<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>
</div>
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·
'.:';;:
<script>
app.controller("Ctrll ",fun
alert($scope.
};
});
return {
restrict: "EA",
scope: {sayName:"&bindAlert"},
});
</script>
</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>
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: "@"
},
});
</script>
</head>
<body ng-app = "app">
<div ng-controller="Ctrl 1 ">
</div>
angular.module('app', rn
.directive('testDirective', function() {
restrict: 'E', controller:
})
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
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,
};
});
</script>
</head>
<body ng-app ="app">
<div test-directive attrl = "attr" attr2 = "attr2">1 am to be
</body>
})
}
};
});
</script>
</head>
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.
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>
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
<script>
var app = angular.module("app",[]);
a pp.controller(" Ctrl 1 ",function($sc
$scope.name= "Smith";
$scope.age= 28;
$scope.alertName = fu
};
});
app.
});
</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>
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.
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',
}
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);
}
}
};
});
return {
require:"productCollection;', link:function(scope, element, attrs,pCCtrl ){
console.log(pCCtrl);
pCCtrl.addltem({name:'brush',price:12});
})
})
</script>
</head>
<body ng-app ="app">
<product-collection
</body>
<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,
$transclude(function( clone){
$element.append( a);
})
}
};
});
</script>
</head>
<body ng-app = "app">
t server communication.
to and fro to server.
learn eve etter and advanced way using the Restful built in API in
better and recommended way of developing the REST APL
$http service
$http({
headers: object,
transform Request: function transform( data, headersGetter) or an array of functions,
Understanding parameters in
Method: The method represents the
GET, POST, and DELETE etc.
this parameter to true will also send the session id with the
request.
<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>
$http.put: put re
$http.delete :
$htt
$http.get('/serverUr .success(successCallback);
$http.post('/ serverUrl ', data).success(successCallback);
$http.get('http://server/api', {
cache: true
}).success(function() {//success handling});
We may also modify the narios, ex: if the server returns JSON
string, we might want · doing our self every time.
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.
<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 -
$scope.errorMsg = $
});
};
});
</script></head>
<body><div ng-app="myModule"
<div ng-controller="MyCtrl">
Handling Restf
$
th server but to make REST requests with
,POST, UPDJ\fE and DELETE. However we
});
ANGULAR JS MATERIAL
A Sen in' fr<J111 0: !\ITS
$scope.fetch = function(id){
}) }
$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> _
{{entry.descri
<div id= "single-c e t"> The comment with id {{id}} has status
{{singleComment.sta and full descriptions as
$scope.entries = Ent
}
});
</script>
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();
Caching in Angularjs ·
The $cacheFactory
acheFactory('AppCachelD'); Here
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.
$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',
});
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
$http({
method: 'GET',
url: '/api/comments.json', cache: appCache
});
angular.module(' Co
.config(functio
});
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.
We now know that there are 2 types of testing. Which testing we use? Unit or End
To End?
Protractor:Protractor is
e2e tests for angular.
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.
Jasmine spec
}); •
What is a Suite
A suite is a collection of specs.
Ex of a suite
it("and has a
exp
1)·
J '
});
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.
The beforeAll function is called only once before all the specs in a describe are run.
As·
functionAddTwoNumbers(a,b) {
var a= 4,b = 3;
beforeEach(function() {
console.log("Setting up ");
a= 4,b =3;
});
afterEach(function() {
a=O,b=O;
});
exp
});
});
it(" Compare Numbers to be Greater Than", function() {
expect(a).toBeGreaterThan(b);
});
});
Ka
If you are using require)s then say yes to the next option. Default is no
--------------------------------------------------------------- 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.
Should any of the files included by the previous patterns be excluded ? You can use glob
patterns, eg. "**/*.swp ".
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.
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.
In the next section we will set up a simple testing project with protractor.
</script>
[]);
$scope.result = parselnt($scope.a)+parselnt($scope.b );
};
});
</script>
</head>
<body ng-app="myModule">
</div>
</div>
Refer to testing/project_e2e/config."
seleniumAddress:'http://localhost.
capabilities:{
},
}
}
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.
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.