AngularJS Tutorial
AngularJS Tutorial
General Features
The general features of AngularJS are as follows −
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.
Core Features
The core features of AngularJS are as follows −
Services − AngularJS comes with several built-in services such as $http 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.
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 from the URL to
the same state.
Concepts
The following diagram depicts some important parts of AngularJS which we will discuss in
detail in the subsequent chapters.
Advantages of AngularJS
The advantages of AngularJS are −
It provides the capability to create Single Page Application in a very clean and
maintainable way.
It provides data binding capability to HTML. Thus, it gives user a rich and responsive
experience.
With AngularJS, the developers can achieve more functionality with short code.
In AngularJS, views are pure html pages, and controllers written in JavaScript do the
business processing.
On the top of everything, AngularJS applications can run on all major browsers and smart
phones, including Android and iOS based phones/tablets.
Disadvantages of AngularJS
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 the application disables JavaScript, then nothing
would be visible, except the basic page.
AngularJS Directives
The AngularJS framework can be divided into three major parts −
ng-bind − This directive binds the AngularJS application data to HTML tags.
When we open the link https://angularjs.org/, we will see there are two options to
download AngularJS library −
View on GitHub − By clicking on this button, we are diverted to GitHub and get all
the latest scripts.
Download AngularJS 1 − By clicking on this button, a screen we get to see a
dialog box shown as −
CDN access − We also have access to a CDN. The CDN gives us access to regional
data centers. In this case, the Google host. The CDN transfers the responsibility of
hosting files from our own servers to a series of external ones. It also offers an
advantage that if the visitor of the web page has already downloaded a copy of
AngularJS from the same CDN, there is no need to re-download it.
We are using the CDN versions of the library throughout this tutorial.
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>
</head>
<script>
angular.module("myapp", [])
.controller("HelloController", function($scope) {
$scope.helloTo = {};
$scope.helloTo.title = "AngularJS";
});
</script>
</body>
</html>
Include AngularJS
We include the AngularJS JavaScript file in the HTML page so that we can use it −
<head>
</script>
</head>
Next, it is required to tell which part of HTML contains the AngularJS app. We can do this
by adding the ng-app attribute to the root HTML element of the AngularJS app. We can
either add it to the html element or the body element as shown below −
<body ng-app = "myapp">
</body>
View
</div>
ng-controller tells AngularJS which controller to use with this view. helloTo.title tells
AngularJS to write the model value named helloTo.title in HTML at this location.
Controller
<script>
angular.module("myapp", [])
.controller("HelloController", function($scope) {
$scope.helloTo = {};
$scope.helloTo.title = "AngularJS";
});
</script>
This code registers a controller function named HelloController in the angular module
named myapp. We will study more about modules and controllers in their respective
chapters. The controller function is registered in angular via the
angular.module(...).controller(...) function call.
The $scope parameter model is passed to the controller function. The controller function
adds a helloTo JavaScript object, and in that object it adds a title field.
Execution
Save the above code as myfirstexample.html and open it in any browser. We get to see the
following output −
What happens when the page is loaded in the browser ? Let us see −
HTML document is loaded into the browser, and evaluated by the browser.
AngularJS JavaScript file is loaded, the angular global object is created.
Next, AngularJS scans through the HTML to search for AngularJS apps as well as
views.
Once the view is located, it connects that view to the corresponding controller
function.
It then renders the views with data from the model populated by the controller. The
page is now ready.
Model − It is the lowest level of the pattern responsible for maintaining data.
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 the Model
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.
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.
AngularJS is a MVC based framework. In the coming chapters, we will see how AngularJS
uses MVC methodology.
ng-bind − This directive binds the AngularJS Application data to HTML tags.
<script
src = "angular.min.js">
</script>
...
</div>
Step 4: Bind the value of above model defined using ng-bind directive
<html>
<head>
</head>
<body>
<h1>Sample Application</h1>
</div>
</script>
</body>
</html>
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-repeat − This directive repeats HTML elements for each item in a collection.
ng-app directive
The ng-app directive starts an AngularJS Application. It defines the root element. It
automatically initializes or bootstraps the application when the web page containing
AngularJS Application is loaded. It is also used to load various AngularJS modules in
AngularJS Application. In the following example, we define a default AngularJS application
using ng-app attribute of a <div> element.
...
</div>
ng-init directive
The ng-init directive initializes an AngularJS Application data. It is used to assign values to
the variables. In the following example, we initialize an array of countries. We use JSON
syntax to define the array of countries.
...
</div>
ng-model directive
The ng-model directive defines the model/variable to be used in AngularJS Application. In
the following example, we define a model named name.
<div ng-app = "">
...
</div>
ng-repeat directive
The ng-repeat directive repeats HTML elements for each item in a collection. In the
following example, we iterate over the array of countries.
...
<ol>
</li>
</ol>
</div>
Example
<html>
<head>
<title>AngularJS Directives</title>
</head>
<body>
<h1>Sample Application</h1>
<ol>
</li>
</ol>
</div>
</script>
</body>
</html>
AngularJS - Expressions
Expressions are used to bind application data to HTML. Expressions are written inside
double curly braces such as in {{ expression}}. Expressions behave similar to ngbind
directives. AngularJS expressions are pure JavaScript expressions and output the data
where they are used.
Using numbers
<p>Expense on Books : {{cost * quantity}} Rs</p>
Using Strings
Using Object
Using Array
<p>Marks(Math): {{marks[3]}}</p>
Example
<html>
<head>
<title>AngularJS Expressions</title>
</head>
<body>
<h1>Sample Application</h1>
student = {firstname:'Mahesh',lastname:'Parashar',rollno:101};
marks = [80,90,75,73,60]">
</div>
</script>
</body>
</html>
AngularJS - Controllers
AngularJS application mainly relies on controllers to control the flow of data in the
application. 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>
<script>
function studentController($scope) {
$scope.student = {
firstName: "Mahesh",
lastName: "Parashar",
fullName: function() {
var studentObject;
studentObject = $scope.student;
};
</script>
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 returns the
combined name.
In the fullName function, we get the student object and then return the combined
name.
As a note, we can also define the controller object in a separate JS file and refer that
file in the HTML page.
Now we can use studentController's student property using ng-model or using expressions
as follows −
<br>
Now whenever we type anything in first name and last name input boxes, we can
see the full name getting updated automatically.
Example
<html>
<head>
<title>Angular JS Controller</title>
</script>
</head>
<body>
<br>
<br>
</div>
<script>
mainApp.controller('studentController', function($scope) {
$scope.student = {
firstName: "Mahesh",
lastName: "Parashar",
fullName: function() {
var studentObject;
studentObject = $scope.student;
};
});
</script>
</body>
</html>
AngularJS - Filters
Filters are used to modify the data. They can be clubbed in expressions or directives using
pipe (|) character. The following list shows the commonly used filters.
1 uppercase
2 lowercase
3 currency
4 filter
Uppercase Filter
Add uppercase filter to an expression using pipe character. Here we've added uppercase
filter to print student name in all capital letters.
Lowercase Filter
Add lowercase filter to an expression using pipe character. Here we've added lowercase
filter to print student name in all lowercase letters.
Currency Filter
Add currency filter to an expression returning number using pipe character. Here we've
added currency filter to print fees using currency format.
Filter
To display only required subjects, we use subjectName as filter.
Subject:
<ul>
<li ng-repeat = "subject in student.subjects | filter: subjectName">
</li>
</ul>
OrderBy Filter
To order subjects by marks, we use orderBy marks.
Subject:
<ul>
</li>
</ul>
Example
<html>
<head>
<title>Angular JS Filters</title>
</script>
</head>
<body>
<tr>
</tr>
<tr>
</tr>
<tr>
</tr>
<tr>
</tr>
</table>
<br/>
<tr>
</tr>
<tr>
</tr>
<tr>
</td>
</tr>
<tr>
<td>Subject:</td>
<td>
<ul>
</li>
</ul>
</td>
</tr>
</table>
</div>
<script>
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}
],
fullName: function() {
var studentObject;
studentObject = $scope.student;
};
});
</script>
</body>
</html>
AngularJS - Tables
Table data is generally repeatable. The ng-repeat directive can be used to draw table
easily. The following example shows the use of ng-repeat directive to draw a table −
<table>
<tr>
<th>Name</th>
<th>Marks</th>
</tr>
</tr>
</table>
<style>
table, th , td {
border-collapse: collapse;
padding: 5px;
table tr:nth-child(odd) {
background-color: #f2f2f2;
table tr:nth-child(even) {
background-color: #ffffff;
}
</style>
Example
<html>
<head>
<title>Angular JS Table</title>
<style>
table, th , td {
border-collapse: collapse;
padding: 5px;
table tr:nth-child(odd) {
background-color: #f2f2f2;
table tr:nth-child(even) {
background-color: #ffffff;
</style>
</head>
<body>
<tr>
</tr>
<tr>
<td>
</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>
</table>
</td>
</tr>
</table>
</div>
<script>
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;
};
});
</script>
</body>
</html>
1 ng-disabled
2 ng-show
3 ng-hide
4 ng-click
represents a AngularJS click event.
ng-disabled Directive
Add ng-disabled attribute to an HTML button and pass it a model. Bind the model to a
checkbox and see the variation.
ng-show Directive
Add ng-show attribute to an HTML button and pass it a model. Bind the model to a
checkbox and see the variation.
ng-hide Directive
Add ng-hide attribute to an HTML button and pass it a model. Bind the model to a
checkbox and see the variation.
ng-click Directive
Add ng-click attribute to an HTML button and update a model. Bind the model to HTML and
see the variation.
Example
<html>
<head>
</head>
<body>
<tr>
</tr>
<tr>
</tr>
<tr>
</tr>
<tr>
</table>
</div>
</script>
</body>
</html>
AngularJS - Modules
AngularJS supports modular approach. Modules are used to separate logic such as services,
controllers, application etc. from the code and maintain the code clean. We define modules
in separate js files and name them as per the module.js file. In the following example, we
are going to create two modules −
Application Module
Here is a file named mainApp.js that contains the following code −
Here, we declare an application mainApp module using angular.module function and pass
an empty array to it. This array generally contains dependent modules.
Controller Module
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;
};
});
Use Modules
...
Here, we use application module using ng-app directive, and controller using ngcontroller
directive. We import the mainApp.js and studentController.js in the main HTML page.
Example
<html>
<head>
<title>Angular JS Modules</title>
<style>
table, th , td {
border-collapse: collapse;
padding: 5px;
table tr:nth-child(odd) {
background-color: #f2f2f2;
table tr:nth-child(even) {
background-color: #ffffff;
</style>
</head>
<body>
<tr>
</tr>
<tr>
</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>
</table>
</td>
</tr>
</table>
</div>
</body>
</html>
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;
};
});
AngularJS - 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
Reset data of a form using on-click directive of a button.
<script>
function studentController($scope) {
$scope.reset = function() {
$scope.firstName = "Mahesh";
$scope.lastName = "Parashar";
$scope.email = "MaheshParashar@tutorialspoint.com";
$scope.reset();
</script>
Validate Data
The following can be used to track error.
Example
<html>
<head>
<title>Angular JS Forms</title>
<style>
table, th , td {
border-collapse: collapse;
padding: 5px;
table tr:nth-child(odd) {
background-color: #f2f2f2;
table tr:nth-child(even) {
background-color: #ffffff;
</style>
</head>
<body>
<tr>
</span>
</td>
</tr>
<tr>
</td>
</tr>
<tr>
</span>
</td>
</tr>
<tr>
<td>
</td>
<td>
studentForm.email.$invalid" ng-click="submit()">Submit</button>
</td>
</tr>
</table>
</form>
</div>
<script>
mainApp.controller('studentController', function($scope) {
$scope.reset = function() {
$scope.firstName = "Mahesh";
$scope.lastName = "Parashar";
$scope.email = "MaheshParashar@tutorialspoint.com";
$scope.reset();
});
</script>
</body>
</html>
AngularJS - Includes
HTML does not support embedding HTML pages within the HTML page. To achieve this
functionality, we can use one of the following options −
Using Ajax − Make a server call to get the corresponding HTML page and set it in
the 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 an HTML page using ng-include
directive.
</div>
Example
<html>
<head>
<title>Angular JS Includes</title>
</script>
<style>
table, th , td {
border-collapse: collapse;
padding: 5px;
table tr:nth-child(odd) {
background-color: #f2f2f2;
}
table tr:nth-child(even) {
background-color: #ffffff;
</style>
</head>
<body>
</div>
<script>
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;
};
});
</script>
</body>
</html>
main.htm
<tr>
</tr>
<tr>
</tr>
<tr>
<td>Name: </td>
<td>{{student.fullName()}}</td>
</tr>
</table>
subjects.htm
<p>Subjects:</p>
<table>
<tr>
<th>Name</th>
<th>Marks</th>
</tr>
</tr>
</table>
Output
To execute this example, we need to deploy testAngularJS.htm, main.htm, and
subjects.htm to a web server. Open the file testAngularJS.htm using the URL of the server
in a web browser and see the result.
AngularJS - Ajax
AngularJS provides $http control which works as a service to read data from the server.
The server makes a database call to get the desired records. AngularJS needs data in JSON
format. Once the data is ready, $http can be used to get the data from server in the
following manner −
function studentController($scope,$https:) {
$https:.get(url).success( function(response) {
$scope.students = response;
});
Here, the file data.txt contains student records. $http service makes an ajax call and sets
response to its property students. students model can be used to draw tables in HTML.
Example
data.txt
"RollNo" : 101,
"Percentage" : "80%"
},
"Percentage" : "70%"
},
"Name" : "Robert",
"RollNo" : 191,
"Percentage" : "75%"
},
"RollNo" : 111,
"Percentage" : "77%"
testAngularJS.htm
<html>
<head>
<title>Angular JS Includes</title>
<style>
table, th , td {
border-collapse: collapse;
padding: 5px;
}
table tr:nth-child(odd) {
background-color: #f2f2f2;
table tr:nth-child(even) {
background-color: #ffffff;
</style>
</head>
<body>
<table>
<tr>
<th>Name</th>
<th>Roll No</th>
<th>Percentage</th>
</tr>
</table>
</div>
<script>
function studentController($scope,$http) {
$http.get(url).then( function(response) {
$scope.students = response.data;
});
</script>
</script>
</body>
</html>
Output
To execute this example, we need to deploy testAngularJS.htm and data.txt file to a web
server. Open the file testAngularJS.htm using the URL of the server in a web browser and
see the result.
AngularJS - Views
AngularJS supports Single Page Application via multiple views on a single page. To do this,
AngularJS has provided ng-view and ng-template directives, and $routeProvider services.
ng-view Directive
The ng-view directive simply creates a place holder where a corresponding view (HTML or
ng-template view) can be placed based on the configuration.
Usage
Define a div with ng-view within the main module.
...
<div ng-view></div>
</div>
ng-template Directive
The 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.
...
{{message}}
</script>
</div>
$routeProvider Service
The $routeProvider is a key service which sets the configuration of URLs, maps them with
the corresponding HTML page or ng-template, and attaches a controller with the same.
Usage 1
Define a script block with type as ng-template within the main module.
...
{{message}}
</script>
</div>
Usage 2
Define a script block with main module and set the routing configuration.
mainApp.config(['$routeProvider', function($routeProvider) {
$routeProvider
.when('/addStudent', {
})
.when('/viewStudents', {
.otherwise ({
redirectTo: '/addStudent'
});
}]);
Example
<html>
<head>
<title>Angular JS Views</title>
</script>
</head>
<body>
<div ng-view></div>
{{message}}
</script>
{{message}}
</script>
</div>
<script>
mainApp.config(['$routeProvider', function($routeProvider) {
$routeProvider
.when('/addStudent', {
templateUrl: 'addStudent.htm',
controller: 'AddStudentController'
})
.when('/viewStudents', {
templateUrl: 'viewStudents.htm',
controller: 'ViewStudentsController'
})
.otherwise({
redirectTo: '/addStudent'
});
}]);
mainApp.controller('AddStudentController', function($scope) {
});
mainApp.controller('ViewStudentsController', function($scope) {
});
</script>
</body>
</html>
AngularJS - Scopes
Scope is a special JavaScript object that connects controller with views. Scope contains
model data. In controllers, model data is accessed via $scope object.
<script>
mainApp.controller("shapeController", function($scope) {
$scope.message = "In shape controller";
$scope.type = "Shape";
});
</script>
The $scope is passed as first argument to controller during its constructor definition.
The $scope.message and $scope.type are the models which are used in the HTML
page.
We assign values to models that are reflected in the application module, whose
controller is shapeController.
Scope Inheritance
Scope is controller-specific. If we define nested controllers, then the child controller inherits
the scope of its parent controller.
<script>
mainApp.controller("shapeController", function($scope) {
$scope.type = "Shape";
});
mainApp.controller("circleController", function($scope) {
});
</script>
The following important points are considered in above example −
Example
<html>
<head>
<title>Angular JS Forms</title>
</head>
<body>
</div>
</div>
</div>
<script src = "angular.min.js">
</script>
<script>
mainApp.controller("shapeController", function($scope) {
$scope.type = "Shape";
});
mainApp.controller("circleController", function($scope) {
});
mainApp.controller("squareController", function($scope) {
$scope.type = "Square";
});
</script>
</body>
</html>
AngularJS - Services
AngularJS supports the concept of Separation of Concerns using services architecture.
Services are JavaScript functions, which are responsible to perform only specific tasks. This
makes them individual entities which are maintainable and testable. The controllers and
filters can call them on requirement basis. Services are normally injected using the
dependency injection mechanism of AngularJS.
AngularJS provides many inbuilt services. For example, $http, $route, $window, $location,
etc. Each service is responsible for a specific task such as the $http is used to make ajax
call to get the server data, the $route is used to define the routing information, and so on.
The inbuilt services are always prefixed with $ symbol.
Factory
Service
mainApp.factory('MathService', function() {
factory.multiply = function(a, b) {
return a * b
return factory;
});
mainApp.service('CalcService', function(MathService) {
this.square = function(a) {
return MathService.multiply(a,a);
});
Example
<html>
<head>
<title>Angular JS Services</title>
</script>
</head>
<body>
<p>Result: {{result}}</p>
</div>
<script>
mainApp.factory('MathService', function() {
var factory = {};
factory.multiply = function(a, b) {
return a * b
return factory;
});
mainApp.service('CalcService', function(MathService) {
this.square = function(a) {
return MathService.multiply(a,a);
});
$scope.square = function() {
$scope.result = CalcService.square($scope.number);
});
</script>
</body>
</html>
Value
Factory
Service
Provider
Constant
Value
Value is a simple JavaScript object, which is required to pass values to the controller during
config phase (config phase is when AngularJS bootstraps itself).
//define a module
mainApp.value("defaultInput", 5);
...
$scope.number = defaultInput;
$scope.result = CalcService.square($scope.number);
$scope.square = function() {
$scope.result = CalcService.square($scope.number);
});
Factory
Factory is a function which is used to return value. It creates a value on demand whenever
a service or a controller requires it. It generally uses a factory function to calculate and
return the value.
//define a module
mainApp.factory('MathService', function() {
factory.multiply = function(a, b) {
return a * b
return factory;
});
//inject the factory "MathService" in a service to utilize the multiply method of factory.
mainApp.service('CalcService', function(MathService) {
this.square = function(a) {
return MathService.multiply(a,a);
});
...
Service
Service is a singleton JavaScript object containing a set of functions to perform certain
tasks. Service is defined using service() function and it is then injected into the controllers.
//define a module
...
mainApp.service('CalcService', function(MathService) {
this.square = function(a) {
return MathService.multiply(a,a);
});
$scope.number = defaultInput;
$scope.result = CalcService.square($scope.number);
$scope.square = function() {
$scope.result = CalcService.square($scope.number);
});
Provider
Provider is used by AngularJS internally to create services, factory, etc. during the config
phase. The following script can be used to create MathService that we created earlier.
Provider is a special factory method with get() method which is used to return the
value/service/factory.
//define a module
...
//create a service using provider which defines a method square to return square of a
number.
mainApp.config(function($provide) {
$provide.provider('MathService', function() {
this.$get = function() {
factory.multiply = function(a, b) {
return a * b;
return factory;
};
});
});
Constant
Constants are used to pass values at the config phase considering the fact that value
cannot be used during the config phase.
Example
<html>
<head>
<title>AngularJS Dependency Injection</title>
</head>
<body>
<p>Result: {{result}}</p>
</div>
</script>
<script>
mainApp.config(function($provide) {
$provide.provider('MathService', function() {
this.$get = function() {
factory.multiply = function(a, b) {
return a * b;
}
return factory;
};
});
});
mainApp.value("defaultInput", 5);
mainApp.factory('MathService', function() {
factory.multiply = function(a, b) {
return a * b;
return factory;
});
mainApp.service('CalcService', function(MathService) {
this.square = function(a) {
return MathService.multiply(a,a);
});
$scope.number = defaultInput;
$scope.result = CalcService.square($scope.number);
$scope.square = function() {
$scope.result = CalcService.square($scope.number);
});
</script>
</body>
</html>
//This directive will be activated as soon as any student element is encountered in html
mainApp.directive('student', function() {
directive.restrict = 'E';
directive.scope = {
student : "=name"
//linkFunction is linked with each element with scope to get the element specific data.
element.css("background-color", "#ff00ff");
return linkFunction;
return directive;
});
Define controller to update the scope for directive. Here we are using name attribute's
value as scope's child.
mainApp.controller('StudentController', function($scope) {
$scope.Mahesh = {};
$scope.Mahesh.rollno = 1;
$scope.Piyush = {};
$scope.Piyush.rollno = 2;
});
Example
<html>
<head>
</head>
<body>
</div>
</script>
<script>
mainApp.directive('student', function() {
directive.restrict = 'E';
student : "=name"
element.css("background-color", "#ff00ff");
return linkFunction;
return directive;
});
mainApp.controller('StudentController', function($scope) {
$scope.Mahesh = {};
$scope.Mahesh.rollno = 1;
$scope.Piyush = {};
});
</script>
</body>
</html>
AngularJS - Internationalization
AngularJS supports inbuilt internationalization for three types of filters : Currency, Date,
and Numbers. We only need to incorporate corresponding java script according to locale of
the country. By default, it considers the locale of the browser. For example, for Danish
locale, use the following script −
</script>
<html>
<head>
<title>Angular JS Forms</title>
</head>
<body>
</div>
</script>
</script>
<script>
mainApp.controller('StudentController', function($scope) {
$scope.fees = 100;
$scope.rollno = 123.45;
});
</script>
</body>
</html>
testAngularJS.htm
<html>
<head>
<title>Angular JS Forms</title>
</head>
<body>
{{rollno | number }}
</div>
</script>
</script> -->
<script>
mainApp.controller('StudentController', function($scope) {
$scope.fees = 100;
$scope.rollno = 123.45;
});
</script>
</body>
</html>