You are on page 1of 74

1

Angular JS
2

MVC Architecture
• MVC stand for Model View
Controller.
• Model View Controller is a software
design pattern for developing web
application. It given software
application into three interconnected
parts.
• Model : It is responsible for
maintaining data.
• View :It is responsible for
displaying output data to the user.
• Controller : It is responsible for
controls the interactions between the
Model and View.
3

 Model:
Represents the data objects. The Model is what is being manipulated
and presented to the user

 View:
Serves as the screen representation of the Model. It is the object that
presents the current state of the data objects.

 Controller:
Defines the way the user interface reacts to the user’s input. The
Controller component is the object that manipulates the Model, or
data object.
4

• 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.

• Angular JS Framework is example of MVC model.


5

MVC Architecture
The Model
•The model is responsible for managing application data.
•It responds to the request from view and to the instructions from
controller to update itself.

The View
•A presentation of data in a particular format, triggered by the controller's
decision to present the data.
•They are script-based template systems such as JSP, ASP, PHP and
very easy to integrate with AJAX technology.

The Controller
•The controller responds to user input and performs interactions on the
data model objects.
•The controller receives input, validates it, and then performs business
operations that modify the state of the data model.
Angular JS
7

Introduction to Angular JS
• AngularJS extends HTML with new attributes

• AngularJS is a JavaScript framework. It can be added to an HTML page


with a <script> tag.
• AngularJS extends HTML attributes with Directives, and binds data to
HTML with Expressions.
• AngularJS is a library written in JavaScript.
• AngularJS is distributed as a JavaScript file, and can be added to a web
page with a script tag:
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/
angular.min.js">
</script>
8

Introduction to Angular JS
AngularJS Extends HTML: AngularJS directives are HTML
attributes with an ng prefix.

1.The ng-app directive defines an AngularJS application.


2.The ng-model directive binds the value of HTML controls (input,
select, textarea) to application data.
3.The ng-bind directive binds application data to the HTML view.
9

Features of Angular JS
10

• Data-binding − It is the automatic synchronization of data between model


and view components.
• Scope − These are objects that refer to the model. They act as a glue between
controller and view.
• Controller − These are JavaScript functions that are bound to a particular
scope.
• Services − AngularJS come with several built-in services for example $https:
to make a XMLHttpRequests. These are singleton objects which are
instantiated only once in app.
• Filters − These select a subset of items from an array and returns a new
array.
• Directives − Directives are markers on DOM elements (such as elements,
attributes, css, and more). These can be used to create custom HTML tags that
serve as new, custom widgets. AngularJS has built-in directives (ngBind,
ngModel...)
11

• Templates − These are the rendered view with information from the
controller and model. These can be a single file (like index.html) or
multiple views in one page using "partials".
• Routing − It is concept of switching views.
• Model View Whatever − MVC 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 you to encode the state of
application in the URL so that it can be bookmarked. The application can
then be restored from the URL to the same state.
• Dependency Injection − AngularJS has a built-in dependency injection
subsystem that helps the developer by making the application easier to
develop, understand, and test.
12

Advantages of Angular JS
• Less Code: It help to write less code. Using AngularJS developers
can achieve more functionality with writing less code.
• Testable: It make your application testable. AngularJS code is unit
testable.
• It increase the level of abstraction.
• It provides reusable components.
• Using this you can design more responsive web pages.
• It help to make and design a big applications.
• AngularJS support most of all new web browser and all mobiles
OS.
• In AngularJS view are pure html code and controller are written in
JavaScript to achieve business logic.
13

Creating Angular JS Application


• AngularJS extends HTML with ng-directives.
1. The ng-app directive defines an AngularJS application.
2. The ng-model directive binds the value of HTML controls (input,
select, textarea) to application data.
3. The ng-bind directive binds application data to the HTML view.
14

Creating Angular JS Application


Step 1: Load framework
•Being a pure JavaScript framework, it can be added using <Script> tag.
<script

src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js">
</script>
Step 2: Define AngularJS application using ng-app directive.
<div ng-app=“ “ > ………..... </div>
Step 3: Define a model name using ng-model directive.
<p>Name: <input type="text" ng-model="name"></p>
Step 4: Bind the value of above model defined using ng-bind directive.
<p ng-bind="name"></p>
Executing AngularJS Application
•Use the above-mentioned three steps in an HTML page.
15

testAngularJS.htm
16

Example of Angular JS
<!DOCTYPE html>
<html>
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js">
</script>
<body>
<div ng-app="">
<p>Input something in the input box:</p>
<p>Name: <input type="text" ng-model="name"></p>
<p ng-bind="name"></p>
</div>
</body>
</html>
Output:-
17

How AngularJS integrates with HTML


• AngularJS starts automatically when the web page has loaded.

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

• The ng-model directive binds the value of the input field to the


application variable name.
• i.e, ng-model directive then creates a model variable named "name"
which can be used with the html page and within the div having ng-
app directive.

• The ng-bind directive binds the innerHTML of the <p> element to the


application variable name

• Closing</div> tag indicates the end of AngularJS application.


18

AngularJS Directives
• AngularJS directives are used to extend HTML. They are special
attributes starting
With ng-prefix. Let us discuss the following directives:
1. ng-app - This directive starts an AngularJS Application.
2. ng-init - This directive initializes application data.
3. ng-model - This directive defines the model that is variable to be
used in AngularJS.
4. ng-repeat - This directive repeats HTML elements for each item
in a collection.
19

AngularJS Directives : 1. ng-app


• The ng-app directive initializes an AngularJS application.
• The ng-app directive also tells AngularJS that the <div> element is
the "owner" of the AngularJS application.
• Using this directive you can tell which part of html contains
Angularjs app. Below we use ng-app with <div> tag.
Syntax: <div ng-app=“ “ > ….... </div>
Example: <div ng-app=“ “ >
Enter text <input type="text" ng-model="name">
<p ng-bind="name"></p> </div>
20

AngularJS Directives : 2. ng-init

• The ng-init directive initialize application data same like variable


initialization in C language, In c language you initialize int a=10;.
• The ng-init directive initializes an AngularJS Application data.
• It is used to assign values to the variables.
Example
<div ng-app="" ng-init="name='Porter'"> // initialize name="Porter"
Name: <input type="text" ng-model="name">
<p>name: {{ name }}</p>
</div>
21

AngularJS Directives : 3. ng-model

• The ng-model directive binds the value of Html controls (input, select,


textarea) to application data.
• The ng-model directive defines the model/variable to be used in
AngularJS Application.
• Provide type validation for application data (number, email, required).
• Provide status for application data (invalid, dirty, touched, error).
• Provide CSS classes for HTML elements.
• Bind HTML elements to HTML forms.
• In the following example, we define a model named name.
Example:
<div ng-app="">
<p> Enter text <input type="text" ng-model="name"> </p>
</div>
22

AngularJS Directives : 4. ng-repeat


• The ng-repeat directive repeats an Html element.
• ng-repeat directive repeats a specific element.
Example
<html>
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js">
</script>
<body> <div ng-app="" ng-init="names=['Jani','Hege','Kai']">
<p>Looping with ng-repeat:</p>
<ul> <li ng-repeat="x in names"> {{ x }} </li> </ul>
</div> </body> </html>

Output: Looping with ng-repeat:


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

AngularJS : Expression

• AngularJS expressions can be written inside double braces: 


{{ expression }}.
• AngularJS expressions can also be written inside a directive: 
ng-bind="expression".

• AngularJS expressions are much like JavaScript expressions:


 They can contain literals, operators, and variables.
Example {{ 5 + 5 }} or {{ firstName + " " + lastName }}
25

AngularJS : Expression
<!DOCTYPE html>
<html>
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js">
</script>
<body>
<div ng-app>
<p>My first expression: {{ 5 + 5 }}</p>
</div>
</body>
</html>
Output: My first expression: 10
//AngularJS expressions bind AngularJS data to HTML the same way
as the ng-bind directive.
26

AngularJS : Expression
• You can write expressions wherever you like, AngularJS will simply
resolve the expression and return the result.
• Example: Let AngularJS change the value of CSS properties.
• Change the color of the input box below, by changing its value:
27
<html>
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js">
</script>
<body>
<p>Change the value of the input field:</p>
<div ng-app="" ng-init="myCol='lightblue'">
<input style="background-color:{{myCol}}"ng-model="myCol"value="
{{myCol}}">
</div>
<p>AngularJS resolves the expression and returns the result.</p>
<p>The background color of the input box will be whatever you write in the
input field.</p>
</body> </html>
28

AngularJS : Expression
AngularJS Strings
•AngularJS strings are like JavaScript strings:
<div ng-app="" ng-init="firstName='John';lastName='Doe'">
<p>The full name is: {{ firstName + " " + lastName }}</p>
</div> Output: The full name is: John Doe
AngularJS Objects
•AngularJS objects are like JavaScript objects:
<div ng-app="" ng-init="person={firstName:'John',lastName:'Doe'}">
<p>The name is :{{ person.lastName }}</p>
</div> Output: The name is: Doe
AngularJS Arrays
•AngularJS arrays are like JavaScript arrays:
<div ng-app="" ng-init="points=[1,15,19,2,40]">
<p>The third result is {{ points[2] }}</p>
</div> Output: The third result is 19
29

AngularJS : Controllers
• AngularJS application mainly relies on controllers to control the
flow of data in the application.
• AngularJS controllers control the data of AngularJS applications.
• A controller is defined using ng-controller directive.
• A controller is a JavaScript object that contains
attributes/properties, and functions.
• Each controller accepts $scope as a parameter, which refers to the
application/module that the controller needs to handle.
<div ng-app="" ng-controller="Controller_Name">
...
</div>
30

<!DOCTYPE html>
AngularJS : Controllers
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js">
</script> <body>
<div ng-app="myApp" ng-controller="myCtrl">
First Name: <input type="text" ng-model="firstName"><br>
Last Name: <input type="text" ng-model="lastName"><br> <br>
Full Name: {{firstName + " " + lastName}}
</div>
<script> var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.firstName = "John";
$scope.lastName = "Doe";
});
</script> </body>
</html>
31

• The AngularJS application is defined by  ng-app="myApp". The


application runs inside the <div>.
• The ng-controller="myCtrl" attribute is an AngularJS directive. It
defines a controller.
• The myCtrl function is a JavaScript function.
• AngularJS will invoke the controller with a $scope object.
• In AngularJS, $scope is the application object (the owner of
application variables and functions).
• The controller creates two properties (variables) in the scope
(firstName andlastName).
• The ng-model directives bind the input fields to the controller
properties (firstName and lastName).
32

AngularJS Scope

• The scope is the binding part between the HTML (view) and the
JavaScript (controller).
• The scope is an object with the available properties and methods.
• The scope is available for both the view and the controller.
• When you make a controller in AngularJS, you pass the $scope object
as an argument:
33

SINHGAD TECHNICAL 13/01/21


EDUCATION SOCIETY
When adding properties to the $scope object in the controller, the view (HTML) gets access to these properties.
34

When adding properties to the $scope object in the controller, the view (HTML) gets
access to these properties.
35

If we consider an AngularJS application to consist of:

• View, which is the HTML.

• Model, which is the data available for the current view.

• Controller, which is the JavaScript function that


makes/changes/removes/controls the data.

• Then the scope is the Model.: The scope is a JavaScript object with
properties and methods, which are available for both the view and
the controller.
36

AngularJS : Modules
• In AngularJS, a module defines an application.
• It is a container for the different parts of your application like
controller, services, filters, directives etc.
• A module is used as a Main() method. Controller always belongs to a
module.
How to create a module
• The angular object's module() method is used to create a module.
• It is also called AngularJS function angular.module
 <div ng-app="myApp">...</div>  
<script>  
var app = angular.module("myApp", []);   
</script>  
• Here, "myApp" specifies an HTML element in which the application
will run.
37

AngularJS : Modules_Add Controller

• Add a controller to your application, and refer to the controller with


the ng-controller directive:
<div ng-app="myApp" ng-controller="myCtrl">
{{ firstName + " " + lastName }}
</div>
<script>
var app = angular.module("myApp", []);
app.controller("myCtrl", function($scope) {
    $scope.firstName = "John";
    $scope.lastName = "Doe";
});
</script>
38

AngularJS : Modules & Controller

• It is common in AngularJS applications to put the module and the controllers


in JavaScript files.
• In this example, "myApp.js" contains an application module definition,
while "myCtrl.js" contains the controller:
myApp.js
var app = angular.module("myApp", []);
• The [] parameter in the module definition can be used to define dependent
modules.
• Without the [] parameter, you are not creating a new module,
but retrieving an existing one.
myCtrl.js
app.controller("myCtrl",function($scope) {
$scope.firstName="John";
$scope.lastName="Doe";
});
39

AngularJS : Modules & Controller


Example: Module_Controller_Combine.html

<!DOCTYPE html>
<html>
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js">
</script>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
{{ firstName + " " + lastName }}
</div>
<script src="myApp.js"></script>
<script src="myCtrl.js"></script>
</body>
</html>
40

AngularJS : Filters
• Filter are mainly used for modify the data.
• Filters can be added to expressions and directives using a pipe (|)
character.
• Following Filter are use in AngularJs;
S.No. Name Description
1 uppercase converts a text to upper case text.
2 lowercase converts a text to lower case text.
3 currency formats text in a currency format.
filter the array to a subset of it based on provided
4 filter
criteria.
5 orderBy orders the array based on provided criteria.
41

AngularJS : Filters:- lowercase and uppercase

• lowercase filter are used for converting upper case text to


lower case text. It is use to expression with pipe (|) character.
{{ LowerCaseName | lowercase }}

• uppercase filter are used for converting lower case text to


upper case text. It is use to expression with pipe (|) character.
{{ UpperCaseName | uppercase }}
42

AngularJS : Filters:- lowercase and uppercase

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js">
</script>
<body>
<div ng-app="myApp" ng-controller="personCtrl">
<p>The lowercase name is : {{ lastName | lowercase }}</p>
<p>The uppercase name is : {{ firstName | uppercase }}</p>
</div>
<script>
angular.module('myApp', []).controller('personCtrl', function($scope) {
$scope.firstName = “Sinhgad",
$scope.lastName = “Sinhgad"
});
</script>
</body>
</html>
43

AngularJS : Filters:- currency


• The currency filter formats a number as currency:
Syntax:
<div ng-app="myApp" ng-controller="costCtrl">
<h1>Price: {{ price | currency }}</h1>
</div>

Example:-
<div ng-app="myApp" ng-controller="costCtrl">
<h1>Price: {{ price | currency }}</h1>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('costCtrl', function($scope) {
$scope.price = 58;
});
</script>
Output: Price: $58.00
44

AngularJS : Filters:- filters

• The AngularJs filter selects a subset of an array.


• The filter can only be used on arrays, and it returns an array
containing only the matching items.
• Example :- Return the names that contains the letter "i":
<div ng-app="myApp" ng-controller="namesCtrl">
<ul>
<li ng-repeat="x in names | filter : 'i'">{{ x }}
</li>
</ul>
</div>
45

AngularJS : Filters:- filters


<!DOCTYPE html>
<html>
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<body> <div ng-app="myApp" ng-controller="namesCtrl">
<ul> <li ng-repeat="x in names | filter : 'i'"> {{ x }} </li> </ul> </div>
<script>
angular.module('myApp', []).controller('namesCtrl', function($scope)
{ $scope.names = [ 'Jani', 'Carl', 'Margareth', 'Hege', 'Joe', 'Gustav', 'Birgit', 'Mary',
'Kai' ];
});
</script>
<p>This example displays only the names containing the letter "i".</p>
</body>
</html>
46

AngularJS : Filters:- orderBy


• To order subjects by marks, we use orderBy marks.
• Subject:
<ul>
<li ng-repeat="subject in student.subjects | orderBy:'marks'">
{{ subject.name + ', marks:' + subject.marks }}
</li>
</ul>
47

AngularJS : Tables
 Table can be styled using CSS
• Table data is generally Styling.
repeatable. The ng-repeat
<style>
directive can be used to draw
table easily. table, th , td { border: 1px solid grey;
<table> border-collapse: collapse; padding:
<tr> 5px;
<th>Name</th> }
<th>Marks</th> table tr:nth-child(odd) {
</tr> background-color: #f2f2f2;
<tr ng-repeat="subject in }
student.subjects"> table tr:nth-child(even) {
<td>{{ subject.name }}</td>
background-color: #ffffff;
<td>{{ subject.marks }}</td>
}
</tr>
</table> </style>
Example: - Table.html
48

AngularJS : Form
• Forms in AngularJS provides data-binding and validation of input
controls.

• Input controls are ways for a user to enter data.

• A form is a collection of controls for the purpose of grouping related


controls together.

Input Controls : Input controls are the HTML input elements:


▫ input elements
▫ select elements
▫ button elements
▫ textarea elements
49

AngularJS : Form : Data Binding


• Input controls provides data-binding by using the ng-model directive.

<input type="text" ng-model="firstname">
• The application does now have a property named firstname.
• The ng-model directive binds the input controller to the rest of your
application.
• The property firstname, can be referred to in a controller:
<script>
var app = angular.module('myApp', []);
app.controller('formCtrl', function($scope) {
$scope.firstname="John";});
</script>
50

AngularJS : Form : Checkbox


• A checkbox has the value true or false. Apply the ng-model directive to a
checkbox, and use its value in your application.
• Example Show the header if the checkbox is checked:
<form> 
Check to show a header:
<input type="checkbox" ng-model="myVar">
</form>
<h1 ng-show="myVar">My Header</h1>
51

AngularJS : Form : Radiobuttons

• Bind radio buttons to your application with the ng-model directive.


• Radio buttons with the same ng-model can have different values, but only
the selected one will be used.
• Example : Display some text, based on the value of the selected radio button:

<form>Pick a topic:
<input type="radio" ng-model="myVar" value="tuts">Tutorials  

  <input type="radio" ng-model="myVar" value="fest">Festivals  
  <input type="radio" ng-model="myVar" value="news">News
</form>
52

AngularJS : Form : Selectbox


• Bind select boxes to your application with the ng-model directive.
• The property defined in the ng-model attribute will have the value of
the selected option in the selectbox.
•  Example
• Display some text, based on the value of the selected option:
<form>Select a topic:
<select ng-model="myVar">
    <option value="">
    <option value="tuts">Tutorials  
 <option value="fest">Festivals  
 <option value="news">News  
</select>
</form>
53

AngularJS : Form : Validation


• AngularJS provides client-side form validation. It checks the state of the
form and input fields (input, textarea, select), and lets you notify the user
about the current state.
• It also holds the information about whether the input fields have been
touched, or modified, or not.
• Following directives are generally used to track errors in an AngularJS
form:
• $dirty - states that value has been changed.
• $invalid - states that value entered is invalid.
• $error - states the exact error.
• $valid-State the value entered is Valid.
54

AngularJS : Include
• HTML does not support embedding html pages within html page. To
achieve this functionality following ways are used −
• Using Ajax − Make a server call to get the corresponding html page and set
it in innerHTML of html control.
• Using Server Side Includes − JSP, PHP and other web side server
technologies can include html pages within a dynamic page.

• Using AngularJS, we can embed HTML pages within a HTML page using
ng-include directive.

<div ng-app = "" ng-controller = "studentController">


<div ng-include=“ 'main.html‘ "></div>
<div ng-include = “ 'subjects.html‘ "></div>
</div>
55

AngularJS : View

• AngularJS supports Single Page Application via multiple views on a


single page.
• AngularJS provides a great way to make single page applications.
When creating single page applications, routing will be very
important. We want our navigation to feel like a normal site and still
not have our site refresh
• To do this AngularJS has provided ng-view and ng-template directives
and $routeProvider services.
ng-view
• ng-view tag simply creates a place holder where a corresponding view
(html or ng-template view) can be placed based on the configuration.
56

13/01/21

Usage
•Define a div with ng-view within the main
module.
<div ng-app = "mainApp">
...
<div ng-view></div> </div>
57

13/01/21

Cont…
Goals
• Single page application
• No page refresh on page change
• Different data on each page
• we'll use Angular's routing capabilities.
58

AngularJS : View
ng-template
•ng-template directive is used to create an html view using script tag.
•It contains "id" attribute which is used by $routeProvider to map a view
with a controller.
Usage
•Define a script block with type as ng-template within the main module.
<div ng-app = "mainApp">
...
<script type = "text/ng-template" id = "addStudent.htm">
<h2> Add Student </h2>
{{message}}
</script>
</div>
59
• // create the module and name it mainApp
• // also include ngRoute for all our routing needs
• Define a script block with main module and set the routing configuration.
var mainApp = angular.module("mainApp", ['ngRoute']);
// configure our routes
mainApp.config(['$routeProvider', function($routeProvider) {
$routeProvider.
// route for the addStudent page
when('/addStudent', { templateUrl: 'addStudent.htm', controller:
'AddStudentController' }).
// route for the viewStudent page
when('/viewStudents', { templateUrl: 'viewStudents.htm', controller:
'ViewStudentsController' }).
otherwise({ redirectTo: '/addStudent' });
}]);
60

AngularJS : View
Following are the important points to be considered in above example.
•$routeProvider is defined as a function under config of mainApp module
using key as '$routeProvider'.
•$routeProvider.when defines a url "/addStudent" which then is mapped to
"addStudent.htm". addStudent.htm should be present in the same path as
main html page.
•"controller" is used to set the corresponding controller for the view.

Example: View.html
61

AngularJS : Scopes
• The Scope is an object that is specified as a binding part between the HTML
(view) and the JavaScript (controller).
• It plays a role of joining controller with the views. It is available for both the
view and the controller.
• Scope contains the model data.
• In controllers, model data is accessed via $scope

<script> var mainApp = angular.module("mainApp", []);


mainApp.controller("shapeController",function($scope){
$scope.message = "In shape controller";
$scope.type = "Shape"; });
</script>
62

AngularJS : Scopes
• Following are the important points to be considered in above example.
• $scope is passed as first argument to controller during its constructor
definition.
• $scope.message and $scope.type are the models which are to be used in the
HTML page.
• We've set values to models which will be reflected in the application module
whose controller is shapeController.
• We can define functions as well in $scope.
63
AngularJS : Scopes Inheritance
• Scope are controllers specific. If we defines nested controllers then child
controller will inherit the scope of its parent controller.
<script> var mainApp = angular.module("mainApp", []);
mainApp.controller("shapeController", function($scope) {
$scope.message = "In shape controller"; $scope.type = "Shape"; });
mainApp.controller("circleController", function($scope) {
$scope.message = "In circle controller"; }); </script>
Following are the important points to be considered in above example.
• We've set values to models in shapeController.
• We've overridden message in child controller circleController.
• When "message" is used within module of controller circleController, the
overridden message will be used.
Example: Scope.html
64

AngularJS : Services
• In AngularJS you can make your own service, or use one of the many
built-in services.
• In AngularJS, a service is a function, or object, that is available for, and
limited to, your AngularJS application.
• AngularJS provides many inbuilt services for example, $https, $route,
$window, $location etc.
• Each service is responsible for a specific task for example,

▫ $https: is used to make ajax call to get the server data.


▫ $route: is used to define the routing information and so
on.
• Inbuilt services are always prefixed with $ symbol.
65

AngularJS : Services- $location


• The $location service has methods which return information about the
location of the current web page:
• Example : Use the $location service in a controller:
var app = angular.module('myApp', []);
app.controller('customersCtrl', function($scope, $location) {
    $scope.myUrl = $location.absUrl();
});
Note that the $location service is passed in to the controller as an
argument. In order to use the service in the controller, it must be defined
as a dependency.
Example: Sevices_location.html
66

AngularJS : Services- $http


• The $http service is one of the most common used services in
AngularJS applications. The service makes a request to the server,
and lets your application handle the response.
• Example :- Use the $http service to request data from the server:

var app = angular.module('myApp', [ ] );
app.controller('myCtrl', function($scope, $http) {
$http.get("welcome.htm").then(function (response) {
$scope.myWelcome = response.data;
});
});
Example: Sevices_http.html
67

AngularJS : Services- $timeout


• The $timeout service is AngularJS version of the
window.setTimeout function.
• Example:- Display a new message after two seconds:
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $timeout) {
$scope.myHeader = "Hello World!";
$timeout(function () {
$scope.myHeader = "How are you today?";
},2000);
});
Example: Sevices_timeout.html
68

AngularJS : Services- $interval


• The $interval service is AngularJS version of the
window.setInterval function.
• Example :- Display the time every second:
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $interval) {
    $scope.theTime = new Date().toLocaleTimeString();
    $interval(function () {
        $scope.theTime = new Date().toLocaleTimeString();
    }, 1000);
});
69

AngularJS : Internationalization
• AngularJS supports inbuilt internationalization for three types of filters
1. currency,
2. date and
3. numbers.
• We only need to incorporate corresponding js according to locale of the
country.
• By default it handles the locale of the browser.
•  For example, to use Danish locale, use following script.
<script src = "https://code.angularjs.org/1.2.5/i18n/angular-locale_da-
dk.js">
</script>
70

AngularJS : Internationalization
• Some of the built-in AngularJS filters supports internationalization.
• For instance, the date and currency filters have built-in support for
internationalization. Here is how you would normally use these filters:
{{ theDate | date: 'fullDate' }}
{{ theValue | currency }}
{{ theValue | number }}
• The date filter will format the variable the Date as a date according to the
locale chosen in the web app.
• The same is true for the currency and number filter.
71

AngularJS : Internationalization- Date


• The date filter accepts the following values specifying how to format the date:
▫ short
▫ medium
▫ fullDate
▫ shortDate
▫ mediumDate
▫ longDate
▫ shortTime
▫ mediumTime
• Here are a few date filter examples:
{{ theDate | date: 'shortDate' }}
{{ theDate | date: 'longDate' }}
72

AngularJS : Internationalization-
Currency
• The currency filter will use the currency symbol associated with the
chosen locale when formatting a number as a currency.
• If you need to use a different currency symbol, for instance if the users
wants to see a price in a different currency, you can specify the
currency symbol to the currency filter like this:
{{ theValue | currency : '$' }}
{{ theValue | currency : '£' }}
{{ theValue | currency : '€' }}
73

AngularJS : Internationalization- Number


• The number filter formats numbers according to the chosen locale.
• For instance, in English the thousand separator is . and the decimal
separator is , whereas in Danish it is the opposite.
• Here is a number filter example:
{{ theValue | number }}
74

AngularJS : Internationalization
Setting the Locale
•To tell AngularJS what locale (language and country) to use when writing
localized output, you need to include the corresponding AngularJS locale
file.
•Here is an example that includes the Danish locale:
<script src="https://code.angularjs.org/1.2.5/i18n/angular-locale_da-dk.js">
</script>
•Include this after including the AngularJS main JavaScript file, and it
should work out of the box.
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.5/angular.min.js">
</script>

You might also like