Note PDF
Note PDF
Note PDF
XML - XML stands for Extensible Mark-up Language, developed by W3C in 1996. It is a
text-based mark-up language derived from Standard Generalized Mark-up Language
(SGML). XML 1.0 was officially adopted as a W3C recommendation in 1998. XML was
designed to carry data, not to display data. XML is designed to be self-descriptive. XML is a
subset of SGML that can define your own tags. A Meta Language and tags describe the
content. XML Supports CSS, XSL, DOM. XML does not qualify to be a programming
language as it does not performs any computation or algorithms. It is usually stored in a
simple text file and is processed by special software that is capable of interpretingXML.
The Difference between XML and HTML
1. HTML is about displaying information, where asXML is about carrying information. In
other words, XML was created to structure, store, and transport information. HTML was
designed to display thedata.
2. Using XML, we can create own tags where as in HTML it is not possible instead it offers
several built intags.
3. XML is platform independent neutral and languageindependent.
4. XML tags and attribute names are case-sensitive where as in HTML it isnot.
5. XML attribute values must be single or double quoted where as in HTML it is not
compulsory.
6. XML elements must be properlynested.
7. All XML elements must have a closingtag.
Well Formed XML Documents
A "Well Formed" XML document must have the following correct XML syntax:
- XML documents must have a rootelement
- XML elements must have a closing tag(start tag must have matching endtag).
- XML tags are casesensitive
- XML elements must be properly nestedEx:<one><two>Hello</two></one>
- XML attribute values must bequoted
XML with correct syntax is "Well Formed" XML. XML validated against a DTD is "Valid"
XML.
What is Markup?
XML is a markup language that defines set of rules for encoding documents in a format that
is both human-readable andmachine-readable.
Example for XML Document
<?xml version="1.0" encoding="UTF-8" standalone="no"?><!—xml declaration-->
<note>
<to>MRCET</to>
<from>MRGI</from>
<heading>KALPANA</heading>
<body>Hello, world! </body>
</note>
Xml document begins with XML declaration statement: <? xml version="1.0"
encoding="ISO-8859-1"?>.
The next line describes the root element of the document:<note>.
This element is "the parent" of all otherelements.
The next 4 lines describe 4child elements of the root: to, from, heading, and body. And
finally the last line defines the end of the root element : </note>.
The XML declaration has no closing tag i.e.</?xml>
The default standalone value is set to no. Setting it to yes tells the processor there are no
external declarations (DTD) required for parsing the document. The file name extension
used for xml program is.xml.
Valid XML document
If an XML document is well-formed and has an associated Document Type Declaration
(DTD), then it is said to be a valid XML document. We will study more about DTD in the
chapter XML - DTDs.
XML DTD
Document Type Definition purpose is to define the structure of an XML document. It defines
the structure with a list of defined elements in the xml document. Using DTD we can specify
the various elements types, attributes and their relationship with one another. Basically DTD
is used to specify the set of rules for structuring data in any XML file.
Why use a DTD?
XML provides an application independent way of sharing data. With a DTD, independent
groups of people can agree to use a common DTD for interchanging data. Your application
can use a standard DTD to verify that data that you receive from the outside world is valid.
You can also use a DTD to verify your own data.
DTD - XML building blocks
Various building blocks of XML are-
1. Elements: The basic entity is element. The elements are used for defining the tags. The
elements typically consist of opening and closing tag. Mostly only one element is used to
define a singletag.
Syntax1: <!ELEMENT element-name (element-content)>
Syntax 2: <!ELEMENT element-name (#CDATA)>
#CDATA means the element contains character data that is not supposed to be parsed by a
parser. or
Syntax 3: <!ELEMENT element-name (#PCDATA)>
#PCDATA means that the element contains data that IS going to be parsed by a parser. or
2. Tags
Tags are used to markup elements. A starting tag like <element_name> mark up the
beginning of an element, and an ending tag like </element_name> mark up the end of an
element.
Examples:
A body element: <body>body text in between</body>.
A message element: <message>some message in between</message>
3. Attribute: The attributes are generally used to specify the values of the element. These are
specified within the double quotes. Ex: <flagtype=‖true‖>
4. Entities
Entities as variables used to define common text. Entity references are references to entities.
Most of you will known the HTML entity reference: " " that is used to insert an extra
space in an HTML document. Entities are expanded when a document is parsed by an XML
parser.
The following entities are predefined in XML:
< (<), >(>), &(&), "(") and '(').
5. CDATA: It stands for character data. CDATA is text that will NOT be parsed by a
parser. Tags inside the text will NOT be treated as markup and entities will not beexpanded.
6. PCDATA: It stands for Parsed Character Data(i.e., text). Any parsed character data should
not contain the markup characters. The markup characters are < or > or &. If we want to use
these characters then make use of < , > or &. Think of character data as the text
found between the start tag and the end tag of an XML element. PCDATA is text that will be
parsed by a parser. Tags inside the text will be treated as markup and entities will be
expanded.
<!DOCTYPE note
[
<!ELEMENT note (to,from,heading,body)>
<!ELEMENT to (#PCDATA)>
<!ELEMENT from (#PCDATA)>
<!ELEMENT heading (#PCDATA)>
<!ELEMENT body (#PCDATA)>
]>
Where PCDATA refers parsed character data. In the above xml document the elements to,
from, heading, body carries some text, so that, these elements are declared to carry text in
DTD file.
This definition file is stored with .dtd extension.
DTD identifier is an identifier for the document type definition, which may be the path to a
file on the system or URL to a file on the internet. If the DTD is pointing to external path, it
is called ExternalSubset.
The square brackets [ ] enclose an optional list of entity declarations called Internal Subset.
Types of DTD:
1. InternalDTD
2. ExternalDTD
1. Internal DTD
A DTD is referred to as an internal DTD if elements are declared within the XML files. To
refer it as internal DTD, standalone attribute in XML declaration must be set to yes. This
means, the declaration works independent of external source.
Syntax:
The syntax of internal DTD is as shown:
<!DOCTYPE root-element [element-declarations]>
Where root-element is the name of root element and element-declarations is where you
declare the elements.
Example:
Following is a simple example of internal DTD:
<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
<!DOCTYPE address [
<!ELEMENT address (name,company,phone)>
<!ELEMENT name (#PCDATA)>
<!ELEMENT company (#PCDATA)>
<!ELEMENT phone (#PCDATA)>
]>
<address>
<name>Kalpana</name>
<company>MRCET</company>
<phone>(040) 123-4567</phone>
</address>
Let us go through the above code:
Start Declaration- Begin the XML declaration with following statement <?xml version="1.0"
encoding="UTF-8" standalone="yes" ?>
DTD- Immediately after the XML header, the document type declaration follows, commonly
referred to as the DOCTYPE:
<!DOCTYPE address [
The DOCTYPE declaration has an exclamation mark (!) at the start of the element name. The
DOCTYPE informs the parser that a DTD is associated with this XML document.
DTD Body- The DOCTYPE declaration is followed by body of the DTD, where you declare
elements, attributes, entities, and notations:
<!ELEMENT address (name,company,phone)>
<!ELEMENT name (#PCDATA)>
<!ELEMENT company (#PCDATA)>
<!ELEMENT phone_no (#PCDATA)>
Several elements are declared here that make up the vocabulary of the <name> document.
<!ELEMENT name (#PCDATA)> defines the element name to be of type "#PCDATA".
Here #PCDATA means parse-able text data. End Declaration - Finally, the declaration
section of the DTD is closed using a closing bracket and a closing angle bracket (]>). This
effectively ends the definition, and thereafter, the XML document followsimmediately.
Rules
The document type declaration must appear at the start of the document (preceded only by
the XML header) — it is not permitted anywhere else within thedocument.
Similar to the DOCTYPE declaration, the element declarations must start with an
exclamationmark.
The Name in the document type declaration must match the element type of the root
element.
External DTD
In external DTD elements are declared outside the XML file. They are accessed by
specifying the system attributes which may be either the legal .dtd file or a valid URL. To
refer it as external DTD, standalone attribute in the XML declaration must be set as no. This
means, declaration includes information from the externalsource.
Syntax Following is the syntax for external DTD:
<!DOCTYPE root-element SYSTEM "file-name">
where file-name is the file with .dtd extension.
Example The following example shows external DTDusage:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE address SYSTEM "address.dtd">
<address>
<name>Kalpana</name>
<company>MRCET</company>
<phone>(040) 123-4567</phone>
</address>
The content of the DTD file address.dtd are as shown:
<!ELEMENT address (name,company,phone)>
<!ELEMENT name (#PCDATA)>
<!ELEMENT company (#PCDATA)>
<!ELEMENT phone (#PCDATA)>
Types
You can refer to an external DTD by using either system identifiers or public identifiers.
SYSTEM IDENTIFIERS
A system identifier enables you to specify the location of an external file containing DTD
declarations. Syntax is as follows:
<!DOCTYPE name SYSTEM "address.dtd" [...]>
As you can see, it contains keyword SYSTEM and a URI reference pointing to the location of
the document.
PUBLIC IDENTIFIERS
Public identifiers provide a mechanism to locate DTD resources and are written as below:
<!DOCTYPE name PUBLIC "-//Beginning XML//DTD Address Example//EN">
As you can see, it begins with keyword PUBLIC, followed by a specialized identifier. Public
identifiers are used to identify an entry in a catalog. Public identifiers can follow any format;
however, a commonly used format is called Formal Public Identifiers, or FPIs.
XML Schemas
XML Schema is commonly known as XML Schema Definition (XSD). It is used to
describe and validate the structure and the content of XML data. XML schema defines the
elements, attributes and data types. Schema element supports Namespaces. It is similar to
a database schema that describes the data in a database. XSD extension is“.xsd”.
This can be used as an alternative to XML DTD. The XML schema became the W#C
recommendation in2001.
XML schema defines elements, attributes, element having child elements, order of child
elements. It also defines fixed and default values of elements andattributes.
XML schema also allows the developer to us datatypes.
<contact xmlns:xsi=http://www.w3.org/2001/XMLSchema-
instancexsi:noNamespaceSchemaLocation=”contact.xsd”>
<name>KALPANA</name>
<company>04024056789</company>
<phone>9876543210</phone>
</contact>
Limitations of DTD:
There is no built-in data type inDTDs.
No new data type can be created inDTDs.
The use of cardinality (no. of occurrences) in DTDs islimited.
Namespaces are notsupported.
DTDs provide very limited support for modularity andreuse.
We cannot put any restrictions on textcontent.
Defaults for elements cannot bespecified.
DTDs are written in a non-XML format and are difficult tovalidate.
Strengths of Schema:
XML schemas provide much greater specificity thanDTDs.
They supports large number of built-in-datatypes.
They arenamespace-aware.
They are extensible to futureadditions.
They support theuniqueness.
It is easier to define data facets (restrictions ondata).
SCHEMA STRUCTURE
The Schema Element
<xs: schema xmlns: xs="http://www.w3.org/2001/XMLSchema">
Element definitions
As we saw in the chapter XML - Elements, elements are the building blocks of XML
document. An element can be defined within an XSD as follows:
<xs:element name="x" type="y"/>
Data types:
These can be used to specify the type of data stored in an Element.
String (xs:string)
Date (xs:date or xs:time)
Numeric (xs:integeror xs:decimal)
Boolean (xs:boolean)
EX: Sample.xsd
<?xml version=‖1.0‖ encoading=‖UTF-8‖?>
<xs:schema xmlns:xs=http://www.w3.org/XMLSchema>
<xs:element name="sname‖ type=‖xs:string"/>
/* <xs:element name="dob” type=”xs:date"/>
<xs:element name="dobtime” type=”xs:time"/>
<xs:element name="marks” type=”xs:integer"/>
<xs:element name="avg” type=”xs:decimal"/>
<xs:element name="flag” type=”xs:boolean"/>*/
</xs:schema>
Sample.xml:
<?xml version=‖1.0‖ encoading=‖UTF-8‖?>
<sname xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="sample.xsd">
Kalpana /*yyyy-mm-dd 23:14:34 600 92.5 true/false */
</sname>
Definition Types
You can define XML schema elements in following ways:
Simple Type - Simple type element is used only in the context of the text. Some of
predefined simple types are: xs:integer, xs:boolean, xs:string, xs:date. Forexample:
<xs:element name="phone_number" type="xs:int" />
<phone>9876543210</phone>
Default and Fixed Values for Simple Elements
In the following example the default value is "red":
<xs:element name="color" type="xs:string" default="red"/>
In the following example the fixed value is "red":
<xs:element name="color" type="xs:string" fixed="red"/>
Complex Type - A complex type is a container for other element definitions. This allows you
to specify which child elements an element can contain and to provide some structure within
your XML documents. For example:
<xs:element name="Address">
<xs:complexType>
<xs:sequence>
<xs:element name="name" type="xs:string"/>
<xs:element name="company" type="xs:string"/>
<xs:element name="phone" type="xs:int" />
</xs:sequence>
</xs:complexType>
</xs:element>
In the above example, Address element consists of child elements. This is a container for
other <xs:element> definitions, that allows to build a simple hierarchy of elements in the
XML document.
Global Types - With global type, you can define a single type in your document, which can
be used by all other references. For example, suppose you want to generalize the person and
company for different addresses of the company. In such case, you can define a general type
as below:
<xs:element name="AddressType">
<xs:complexType>
<xs:sequence>
<xs:element name="name" type="xs:string"/>
<xs:element name="company" type="xs:string"/>
</xs:sequence>
</xs:complexType>
</xs:element>
Now let us use this type in our example as below:
<xs:element name="Address1">
<xs:complexType>
<xs:sequence>
<xs:element name="address" type="AddressType" />
<xs:element name="phone1" type="xs:int" />
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name="Address2">
<xs:complexType>
<xs:sequence>
<xs:element name="address" type="AddressType" />
<xs:element name="phone2" type="xs:int" />
</xs:sequence></xs:complexType></xs:element>
Instead of having to define the name and the company twice (once for Address1 and once for
Address2), we now have a single definition. This makes maintenance simpler, i.e., if you
decide to add "Postcode" elements to the address, you need to add them at just one place.
Attributes
Simple elements cannot have attributes. If an element has attributes, it is considered to be of a
complex type. But the attribute itself is always declared as a simple type. Attributes in XSD
provide extra information within an element. Attributes have name and type property as
shown below:
<xs:attribute name="x" type="y"/>
Ex: <lastname lang="EN">Smith</lastname>
<xs:attribute name="lang" type="xs:string"/>
Default and Fixed Values for Attributes
<xs:attribute name="lang" type="xs:string" default="EN"/>
<xs:attribute name="lang" type="xs:string" fixed="EN"/>
Optional and Required Attributes
Attributes are optional by default. To specify that the attribute is required, use the "use"
attribute:
<xs:attribute name="lang" type="xs:string" use="required"/>
Restrictions on Content
When an XML element or attribute has a data type defined, it puts restrictions on the
element's or attribute's content. If an XML element is of type "xs:date" and contains a string
like "Hello World", the element will not validate.
Restrictions on Values:
The value of age cannot be lower than 0 or greater than 120:
<xs:element name="age">
<xs:simpleType>
<xs:restriction base="xs:integer">
<xs:minInclusive value="0"/>
<xs:maxInclusive value="120"/>
</xs:restriction>
</xs:simpleType></xs:element>
XSD Indicators
We can control HOW elements are to be used in documents with indicators.
Indicators: There are seven indicators
Order indicators:
All
Choice
Sequence
Occurrence indicators:
maxOccurs
minOccurs
Group indicators:
Groupname
attributeGroupname
Order Indicators
Order indicators are used to define the order of the elements.
All Indicator
The <all> indicator specifies that the child elements can appear in any order, and that each
child element must occur only once:
<xs:element name="person">
<xs:complexType>
<xs:all>
<xs:element name="firstname"type="xs:string"/>
<xs:element name="lastname"type="xs:string"/>
</xs:all>
</xs:complexType>
</xs:element>
Note: When using the <all> indicator you can set the <minOccurs> indicator to 0 or 1 and the
<maxOccurs> indicator can only be set to 1 (the <minOccurs> and <maxOccurs> are
described later).
Choice Indicator
The <choice> indicator specifies that either one child element or another can occur:
<xs:element name="person">
<xs:complexType>
<xs:choice>
<xs:element name="employee" type="employee"/>
<xs:element name="member" type="member"/>
</xs:choice></xs:complexType> </xs:element>
Sequence Indicator
The <sequence> indicator specifies that the child elements must appear in a specific order:
<xs:element name="person">
<xs:complexType>
<xs:sequence>
<xs:element name="firstname" type="xs:string"/>
<xs:element name="lastname" type="xs:string"/>
</xs:sequence></xs:complexType></xs:element>
Occurrence Indicators
Occurrence indicators are used to define how often an element can occur.
Note: For all "Order" and "Group" indicators (any, all, choice, sequence, group name, and group
reference) the default value for maxOccurs and minOccurs is 1.
maxOccurs Indicator
The <maxOccurs> indicator specifies the maximum number of times an element can occur:
<xs:element name="person">
<xs:complexType>
<xs:sequence>
<xs:element name="full_name" type="xs:string"/>
<xs:element name="child_name" type="xs:string" maxOccurs="10"/>
</xs:sequence>
</xs:complexType>
</xs:element>
minOccurs Indicator
The <minOccurs> indicator specifies the minimum number of times an element can occur:
<xs:element name="person">
<xs:complexType>
<xs:sequence>
<xs:element name="full_name" type="xs:string"/>
<xs:element name="child_name" type="xs:string" maxOccurs="10" minOccurs="0"/>
</xs:sequence>
</xs:complexType>
</xs:element>
Tip: To allow an element to appear an unlimited number of times, use the
maxOccurs="unbounded" statement:
You must define an all, choice, or sequence element inside the group declaration. The
following example defines a group named "persongroup", that defines a group of elements
that must occur in an exact sequence:
<xs:group name="persongroup">
<xs:sequence>
<xs:element name="firstname" type="xs:string"/>
<xs:element name="lastname" type="xs:string"/>
<xs:element name="birthday" type="xs:date"/>
</xs:sequence>
</xs:group>
After you have defined a group, you can reference it in another definition, like this:
<xs:element name="person" type="personinfo"/>
<xs:complexType name="personinfo">
<xs:sequence>
<xs:group ref="persongroup"/>
<xs:element name="country" type="xs:string"/>
</xs:sequence>
</xs:complexType>
Attribute Groups
Attribute groups are defined with the attributeGroup declaration, like this:
<xs:attributeGroup name="groupname">
...
</xs:attributeGroup>
The following example defines an attribute group named "personattrgroup":
<xs:attributeGroup name="personattrgroup">
<xs:attribute name="firstname" type="xs:string"/>
<xs:attribute name="lastname" type="xs:string"/>
<xs:attribute name="birthday" type="xs:date"/>
</xs:attributeGroup>
After you have defined an attribute group, you can reference it in another definition, like this:
<xs:element name="person">
<xs:complexType>
<xs:attributeGroup ref="personattrgroup"/></xs:complexType></xs:element>
<city>4000 Stavanger</city>
<country>Norway</country>
</shipto>
<item>
<title>Empire Burlesque</title>
<note>Special Edition</note>
<quantity>1</quantity>
<price>10.90</price>
</item>
<item>
<title>Hide yourheart</title> <quantity>1</quantity>
<price>9.90</price></item>
</shiporder>
Create an XML Schema "shiporder.xsd":
<?xml version="1.0" encoding="UTF-8" ?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="shiporder">
<xs:complexType>
<xs:sequence>
<xs:element name="orderperson" type="xs:string"/>
<xs:element name="shipto">
<xs:complexType>
<xs:sequence>
<xs:element name="name" type="xs:string"/>
<xs:element name="address" type="xs:string"/>
<xs:element name="city" type="xs:string"/>
<xs:element name="country" type="xs:string"/>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name="item" maxOccurs="unbounded">
<xs:complexType>
<xs:sequence>
<xs:element name="title" type="xs:string"/>
<xs:element name="note" type="xs:string" minOccurs="0"/>
<xs:element name="quantity" type="xs:positiveInteger"/>
<xs:element name="price" type="xs:decimal"/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
<xs:attribute name="orderid" type="xs:string" use="required"/>
</xs:complexType>
</xs:element>
</xs:schema>
You can then manipulate the object model in any way that makes sense. This mechanism is
also known as the "random access" protocol, because you can visit any part of the data at any
time. You can then modify the data, remove it, or insert new data.
The XML DOM, on the other hand, also provides an API that allows a developer to add, edit,
move, or remove nodes in the tree at any point in order to create an application. A DOM
parser creates a tree structure in memory from the input document and then waits for requests
from client. A DOM parser always serves the client application with the entire document no
matter how much is actually needed by the client. With DOM parser, method calls in client
application have to be explicit and forms a kind of chained method calls.
Document Object Model is for defining the standard for accessing and manipulating XML
documents. XML DOM is used for
Loading the xmldocument
Accessing the xmldocument
Deleting the elements of xmldocument
Changing the elements of xml document
According to the DOM, everything in an XML document is a node. It considers
The entire document is a documentnode
Every XML element is an elementnode
The text in the XML elements are textnodes
Every attribute is an attributenode
Comments are comment nodes
#document <html>
<body> BODY
HTML <h1>Heading 1</h1>
lastChild
parentNode
<p>Paragraph.</p>
firstChild
HEAD
<h2>Heading 2</h2>
<p>Paragraph.</p>
BODY </body> nextSibling nextSibling nextSibling
</html>
H1
#text
H1 P H2 P
previousSibling previousSibling previousSibling
parentNode
parentNode
parentNode
parentNode
P
firstChild
firstChild
firstChild
firstChild
lastChild
lastChild
lastChild
lastChild
#text
H2
#text
ANGUALR JS :
GeneralFeatures
AngularJS is a efficient framework that can create Rich Internet Applications (RIA).
AngularJS provides developers an options to write client side applications using JavaScript in a
clean Model View Controller (MVC) way.
AngularJS is open source, completely free, and used by thousands of developers around the
world. It is licensed under the Apache license version 2.0.
CoreFeatures
Scope: These are objects that refer to the model. They act as a glue betweencontroller and view.
1
Downloaded by Shiva Gopi Boddu ([email protected])
lOMoARcPSD|49748193
Angular
JS
Controller: These are JavaScript functions bound to a particular scope.
Services: AngularJS comes with several built-in services such as $http to make a
XMLHttpRequests. These are singleton objects which are instantiatedonly once in app.
Filters: These select a subset of items from an array and returns a new array.
Directives: Directives are markers on DOM elements such as elements, attributes, css, and more.
These can be used to create custom HTML tags thatserve as new, custom widgets. AngularJS has
built-in directives such as ngBind, ngModel, etc.
Templates: These are the rendered view with information from the controller and model. These
can be a single file (such as index.html) or multiple views in one page using partials.
Model View Whatever: MVW is a design pattern for dividing an application into different parts
called Model, View, and Controller, each with distinct responsibilities. AngularJS does not
implement MVC in the traditional sense, but rather something closer to MVVM (Model-View-
ViewModel). The Angular JS team refers it humorously as Model View Whatever.
Deep Linking: Deep linking allows to encode the state of application in the URL so that it can
be bookmarked. The application can then be restored fromthe URL to the same state.
Dependency Injection: AngularJS has a built-in dependency injection subsystem that helps the
developer to create, understand, and test the applications easily.
Concepts
Angular
JS
AdvantagesofAngularJS
It provides data binding capability to HTML. Thus, it gives user a rich andresponsive
experience.
With AngularJS, the developers can achieve more functionality with shortcode.
In AngularJS, views are pure html pages, and controllers written in JavaScriptdo the business
processing.
Angular
JS
On the top of everything, AngularJS applications can run on all major
browsers and smart phones, including Android and iOS based
phones/tablets.
DisadvantagesofAngularJS
Though AngularJS comes with a lot of merits, here are some points of concern:
Not secure : Being JavaScript only framework, application written in AngularJS are not safe.
Server side authentication and authorization is must to keep an application secure.
Not degradable: If the user of your application disables JavaScript, then nothing would be
visible, except the basic page.
AngularJSDirectives
ng-model : This directive binds the values of AngularJS application data to HTML input
controls.
ng-bind : This directive binds the AngularJS application data to HTML tag
Example
Now let us write a simple example using AngularJS library. Let us create
an HTML file myfirstexample.html shown as below:
<!doctype html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.0-
beta.17/angular.min.js"></script>
</head>
<body ng-app="myapp">
<div ng-controller="HelloController" >
<h2>Welcome {{helloTo.title}} to the world of Tutorialspoint!</h2>
</div>
<script>
angular.module("myapp", [])
.controller("HelloController", function($scope) {
$scope.helloTo = {};
$scope.helloTo.title = "AngularJS";
});
</script>
</body>
</html>
5
Downloaded by Shiva Gopi Boddu ([email protected])
lOMoARcPSD|49748193
Include AngularJS
We include the AngularJS JavaScript file in the HTML page so that we can use it:
<head>
<script
src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js"></script>
</head>
You can check the latest version of AngularJS on its official website.
<body ng-app="myapp">
</body>
View
The view is this part:
Controller
The controller part is:
<script>
angular.module("myapp", [])
.controller("HelloController", function($scope) {
$scope.helloTo = {};
$scope.helloTo.title = "AngularJS";
});
6
Downloaded by Shiva Gopi Boddu ([email protected])
lOMoARcPSD|49748193
</script>
View - It is responsible for displaying all or a portion of the data to the user.
Controller - It is a software Code that controls the interactions between theModel and View.
MVC is popular because it isolates the application logic from the user
interface layer and supports separation of concerns. The controller receives
all requests for the application and then works with the model to prepare
any data needed by the view. The view then uses the data prepared by the
controller to generate a final presentable response. The MVC abstraction can
be graphically represented as follows.
Before creating actual Hello World ! application using AngularJS, let us see
the parts of a AngularJS application. An AngularJS application consists of
following three important parts:
ng-app : This directive defines and links an AngularJS application to HTML.
ng-model : This directive binds the values of AngularJS application data toHTML input
controls.
ng-bind : This directive binds the AngularJS Application data to HTML tags.
CreatingAngularJSApplication
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js">
</script>
<div ng-app="">
...
</div>
Step 4: Bind the value of above model defined using ng-bind directive.
testAngularJS.htm
<html>
<title>AngularJS First Application</title>
<body>
<h1>Sample Application</h1>
<div ng-app="">
<p>Enter your Name: <input type="text" ng-model="name"></p>
<p>Hello <span ng-bind="name"></span>!</p>
</div>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js">
</script>
</body>
</html>
Output
Open the file testAngularJS.htm in a web browser. Enter your name and see theresult.
HowAngularJSIntegrateswithHTML
The ng-bind then uses the name model to be displayed in the HTML <span>tag whenever user
enters input in the text box.
ng-model - This directive defines the model that is variable to be used inAngularJS.
ng-repeat - This directive repeats HTML elements for each item in acollection.
ng-appdirective
<div ng-app="">
...
</div>
ng-initdirective
...
</div>
10
Downloaded by Shiva Gopi Boddu ([email protected])
lOMoARcPSD|49748193
ng-modeldirective
<div ng-app="">
...
<p>Enter your Name: <input type="text" ng-model="name"></p>
</div>
ng-repeatdirective
The ng-repeat directive repeats HTML elements for each item in a collection.
In the following example, we iterate over the array of countries.
<div ng-app="">
...
<p>List of Countries with locale:</p>
<ol>
<li ng-repeat="country in countries">
{{ 'Country: ' + country.name + ', Locale: ' + country.locale }}
</li>
</ol>
</div>
Example
The following example shows the use of all the above-mentioned directives.
testAngularJS.htm
<html>
<title>AngularJS Directives</title>
<body>
<h1>Sample Application</h1>
<div ng-app="" ng-init="countries=[{locale:'en-US',name:'United States'},
{locale:'en-GB',name:'United Kingdom'},
{locale:'en-FR',name:'France'}]">
<p>Enter your Name: <input type="text" ng-model="name"></p>
11
Downloaded by Shiva Gopi Boddu ([email protected])
lOMoARcPSD|49748193
Using numbers
Using String
Using Array
<p>Marks(Math): {{marks[3]}}</p>
Example
The following example shows the use of all the above-mentioned expressions:
testAngularJS.htm
<html>
<title>AngularJS Expressions</title>
<body>
<h1>Sample Application</h1>
<div ng-app="" ng-init="quantity=1;cost=30;
student={firstname:'Mahesh',lastname:'Parashar',rollno:101};marks=[80,90,75,73,60]">
<p>Hello {{student.firstname + " " + student.lastname}}!</p>
<p>Expense on Books : {{cost * quantity}} Rs</p>
<p>Roll No: {{student.rollno}}</p>
<p>Marks(Math): {{marks[3]}}</p>
Output
Open the file testAngularJS.htm in a web browser and see the result.
12
Downloaded by Shiva Gopi Boddu ([email protected])
lOMoARcPSD|49748193
13
Downloaded by Shiva Gopi Boddu ([email protected])
lOMoARcPSD|49748193
Angular
<script>
function studentController($scope) {
$scope.student = { firstName:
"Mahesh", lastName:
"Parashar",fullName:
function() {
var studentObject; studentObject =
$scope.student;
return studentObject.firstName + " " + studentObject.lastName;
}
};
}
</script>
The studentController is defined as a JavaScript object with $scope as anargument.
The firstName and the lastName are two properties of $scope.student object.We pass the default
values to them.
The property fullName is the function of $scope.student object, which returnsthe combined name.
14
Downloaded by Shiva Gopi Boddu ([email protected])
lOMoARcPSD|49748193
Angular
JS
In the fullName function, we get the student object and then return thecombined name.
As a note, we can also define the controller object in a separate JS file andrefer that file in the
HTML page.
Example
The following example shows the use of controller:
testAngularJS.htm
<html>
<head>
<title>Angular JS Controller</title>
</head>
<body>
<h2>AngularJS Sample Application</h2>
<div ng-app="" ng-controller="studentController">
Enter first name: <input type="text" ng-model="student.firstName"><br><br>Enter last name:
<input type="text" ng-model="student.lastName"><br>
<br>
You are entering: {{student.fullName()}}
</div>
<script>
function studentController($scope) {
$scope.student = {
firstName: "Mahesh",
15
Downloaded by Shiva Gopi Boddu ([email protected])
lOMoARcPSD|49748193
lastName: "Parashar",
fullName: function() {
var studentObject; studentObject =
$scope.student;
return studentObject.firstName + " " + studentObject.lastName;
}
};
}
</script>
<script
src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js">
</script>
</body>
</html>
Output
Open the file testAngularJS.htm in a web browser and see the result.
16
Downloaded by Shiva Gopi Boddu ([email protected])
lOMoARcPSD|49748193
The following directives are used to bind application data to the attributes
of HTML DOM elements:
Name Description
ng-disabledDirective
Add ng-disabled attribute to an HTML button and pass it a model. Bind the
model to a checkbox and see the variation.
ng-showDirective
Add ng-show attribute to an HTML button and pass it a model. Bind the
model to a checkbox and see the variation.
ng-hideDirective
Add ng-hide attribute to an HTML button and pass it a model. Bind the
model to a checkbox and see the variation.
17
Downloaded by Shiva Gopi Boddu ([email protected])
lOMoARcPSD|49748193
Angular
JS
ng-clickDirective
Add ng-click attribute to an HTML button and update a model. Bind the
model to HTML and see the variation.
Example
The following example shows use of all the above mentioned directives.
testAngularJS.htm
<html>
<head>
<title>AngularJS HTML DOM</title>
</head>
<body>
<h2>AngularJS Sample Application</h2>
<div ng-app="">
<table border="0">
<tr>
<td><input type="checkbox" ng-model="enableDisableButton">DisableButton</td>
<td><button ng-disabled="enableDisableButton">Click Me!</button></td>
</tr>
<tr>
<td><input type="checkbox" ng-model="showHide1">Show Button</td>
<td><button ng-show="showHide1">Click Me!</button></td>
</tr>
<tr>
<td><input type="checkbox" ng-model="showHide2">Hide Button</td>
<td><button ng-hide="showHide2">Click Me!</button></td>
</tr>
<tr>
<td><p>Total click: {{ clickCounter }}</p></td>
<td><button ng-click="clickCounter = clickCounter + 1">Click
18
Downloaded by Shiva Gopi Boddu ([email protected])
lOMoARcPSD|49748193
Angular
JS
Me!</button></td>
</tr>
</table>
</div>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js">
</script>
</body>
</html>
Output
Open the file testAngularJS.htm in a web browser and see the result.
19
Downloaded by Shiva Gopi Boddu ([email protected])
lOMoARcPSD|49748193
ApplicationModule
ControllerModule
studentController.js
mainApp.controller("studentController", function($scope) {
$scope.student = { firstName:
"Mahesh", lastName:
"Parashar",fees:500,
subjects:[
{name:'Physics',marks:70},
{name:'Chemistry',marks:80},
{name:'Math',marks:65},
{name:'English',marks:75},
{name:'Hindi',marks:67}
],
fullName: function() {var
studentObject;
20
Downloaded by Shiva Gopi Boddu ([email protected])
lOMoARcPSD|49748193
Angular
JS
studentObject = $scope.student;
return studentObject.firstName + " " + studentObject.lastName;
}
};
});
Here, we declare a controller studentController module using mainApp.controllerfunction.
UseModules
Example
The following example shows use of all the above mentioned modules.
testAngularJS.htm
21
Downloaded by Shiva Gopi Boddu ([email protected])
lOMoARcPSD|49748193
Angular
JS
}
</style>
</head>
<body>
<h2>AngularJS Sample Application</h2>
<div ng-app="mainApp" ng-controller="studentController">
<table border="0">
<tr><td>Enter first name:</td><td><input type="text" ng-
model="student.firstName"></td></tr>
<tr><td>Enter last name: </td><td><input type="text" ng-
model="student.lastName"></td></tr>
<tr><td>Name: </td><td>{{student.fullName()}}</td></tr>
<tr><td>Subject:</td><td>
<table>
<tr>
<th>Name</th>
<th>Marks</th>
</tr>
<tr ng-repeat="subject in student.subjects">
<td>{{ subject.name }}</td>
<td>{{ subject.marks }}</td>
</tr>
</table>
</td></tr>
</table>
</div>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js">
</script>
<script src="mainApp.js"></script>
<script src="studentController.js"></script>
</body>
</html>
22
Downloaded by Shiva Gopi Boddu ([email protected])
lOMoARcPSD|49748193
Angular
JS
mainApp.js
studentController.js
mainApp.controller("studentController", function($scope) {
$scope.student = { firstName:
"Mahesh", lastName:
"Parashar",fees:500,
subjects:[
{name:'Physics',marks:70},
{name:'Chemistry',marks:80},
{name:'Math',marks:65},
{name:'English',marks:75},
{name:'Hindi',marks:67}
],
fullName: function() {var
studentObject;
studentObject = $scope.student;
return studentObject.firstName + " " + studentObject.lastName;
}
};
});
Output
Open the file textAngularJS.htm in a web browser. See the result.
23
Downloaded by Shiva Gopi Boddu ([email protected])
lOMoARcPSD|49748193
Angular
JS
24
Downloaded by Shiva Gopi Boddu ([email protected])
lOMoARcPSD|49748193
Angular
12. FORMS
AngularJS enriches form filling and validation. We can use ng-click event to
handle the click button and use $dirty and $invalid flags to do the validation
in a seamless way. Use novalidate with a form declaration to disable any
browser-specific validation. The form controls make heavy use of AngularJS
events. Let us have a look at the events first.
Events
AngularJS provides multiple events associated with the HTML controls. For
example, ng-click directive is generally associated with a button. AngularJS
supports the following events:
ng-click
ng-dbl-click
ng-mousedown
ng-mouseup
ng-mouseenter
ng-mouseleave
ng-mousemove
ng-mouseover
ng-keydown
ng-keyup
ng-keypress
ng-change
ng-click
25
Downloaded by Shiva Gopi Boddu ([email protected])
lOMoARcPSD|49748193
Angular
JS
$scope.reset = function(){
$scope.firstName = "Mahesh";
$scope.lastName = "Parashar";
$scope.email = "[email protected]";
}
$scope.reset();
}
</script>
ValidateData
Example
The following example will showcase all the above-mentioned directives.
testAngularJS.htm
<html>
<head>
<title>Angular JS Forms</title>
<style>
table, th , td {
border: 1px solid grey; border-
collapse: collapse;padding: 5px;
}
table tr:nth-child(odd) {
background-color: #f2f2f2;
}
table tr:nth-child(even) {
background-color: #ffffff;
}
26
Downloaded by Shiva Gopi Boddu ([email protected])
lOMoARcPSD|49748193
Angular
JS
</style>
</head>
<body>
<h2>AngularJS Sample Application</h2>
<div ng-app="" ng-controller="studentController">
<form name="studentForm" novalidate>
<table border="0">
<tr><td>Enter first name:</td><td><input name="firstname" type="text"ng-
model="firstName" required>
<span style="color:red" ng-show="studentForm.firstname.$dirty &&
studentForm.firstname.$invalid">
<span ng-show="studentForm.firstname.$error.required">First Name isrequired.</span>
</span>
</td></tr>
<tr><td>Enter last name: </td><td><input name="lastname" type="text" ng-model="lastName" required>
<span style="color:red" ng-show="studentForm.lastname.$dirty &&studentForm.lastname.$invalid">
<span ng-show="studentForm.lastname.$error.required">Last Name isrequired.</span>
</span>
</td></tr>
<tr><td>Email: </td><td><input name="email" type="email" ng-model="email"
length="100" required>
<span style="color:red" ng-show="studentForm.email.$dirty &&
studentForm.email.$invalid">
<span ng-show="studentForm.email.$error.required">Email isrequired.</span>
<span ng-show="studentForm.email.$error.email">Invalid emailaddress.</span>
</span>
</td></tr>
<tr><td><button ng-click="reset()">Reset</button></td><td><buttonng-
disabled=
27
Downloaded by Shiva Gopi Boddu ([email protected])
lOMoARcPSD|49748193
Angular
JS
Output
Open the file testAngularJS.htm in a web browser and see the result.
28
Downloaded by Shiva Gopi Boddu ([email protected])
lOMoARcPSD|49748193
Angular
JS
29
Downloaded by Shiva Gopi Boddu ([email protected])
lOMoARcPSD|49748193
Angular
JS