WEBX Module3
WEBX Module3
INTRODUCTION TO ANGULARJS
CO3: Build single page applications with AngularJS
Contents:
Overview of AngularJS
Need of AngularJS in real web sites
AngularJS Modules
AngularJS built-in directives
AngularJS custom directives
AngularJS expression
AngularJS data binding
AngularJS filters
AngularJS controllers
AngularJS scope
AngularJS dependency injection
AngularJS services
Form validation
Routing using ng-route,ng-repeat,ng-style,ng-view using anglarJS with Typescript
AngularJS Overview
AngularJS is an open-source web application framework. It was originally developed in 2009 by Misko
Hevery and Adam Abrons. It is now maintained by Google. Its latest version is 1.8.3
• 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.
• Applications written in AngularJS are cross-browser compliant. AngularJS automatically
handles JavaScript code suitable for each browser.
• 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.
Overall, AngularJS is a framework to build large scale, high-performance, and easy to-maintain web
applications.
Core Features
• 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 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 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 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.
Core Features
• 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.
• AngularJS code is unit testable.
• AngularJS uses dependency injection and make use of separation of concerns.
• AngularJS provides reusable components.
• 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
• 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.
MVC Model
Model View Controller or MVC as it is popularly called, is a software design pattern for
developing web applications. A Model View Controller pattern is made up of the following
three parts −
• 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.
Directives in AngularJS:
Step 4: Bind the value of above model defined using ng-bind directive
<p>Hello <span ng-bind = "name"></span>!</p>
How AngularJS Integrates with HTML
2. Using Strings
<p>Hello {{student.firstname + " " + student.lastname}}!</p>
3. Using Object
<p>Roll No: {{student.rollno}}</p>
4. Using Array
<p>Marks(Math): {{marks[3]}}</p>
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.
1. Here, we declare a controller named studentController, using the ng-controller directive
2. We define it as follows −
3. Now we can use studentController's student property using ng-model or using expressions
as follows −
Note-
•We bound student.firstName and student.lastname to two input boxes.
•We bound student.fullName() to HTML.
•Now whenever you type anything in first name and last name input boxes, you can see the full name getting
updated automatically.
AngularJS - Filters
❖ Lowercase Filter
❖ Currency Filter Add currency filter to an expression returning number using pipe character
❖ OrderBy Filter
AngularJS modules
Here, we declare an application mainApp module using angular.module function and pass an empty array
to it. This array generally contains dependent modules.
2. Controller Module
studentController.js
Here, we use application module using ng-app directive, and controller using ng-controller directive. We import the
mainApp.js and studentController.js in the main HTML page
For Example :
<html>
<head>
<title>AngularJS Directives</title>
</head>
<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>
<script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js">
</script>
</body>
</html>
AngularJS scope
<input ng-model="name">
</div>
<script>
app.controller('myCtrl', function($scope)
{
$scope.name = “Pragati Patil";
});
</script>
Dependency Injection
• 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).
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.
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.
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.
Constant:
Constants are used to pass values at the config phase considering the fact that value cannot be used
during the config phase.
mainApp.constant("configParam", "constant value");
<html><head> mainApp.value("defaultInput", 5);
<title>AngularJS Dependency Injection</title></head> mainApp.factory('MathService', function() {
<body><h2>AngularJS Sample Application</h2>
var factory = {};
<div ng-app = "mainApp" ng-controller = "CalcController"> factory.multiply = function(a, b) {
<p>Enter a number: <input type = "number" ng-model = return a * b;
"number" /> </p>
<button ng-click = "square()">X<sup>2</sup> </button> }
<p>Result: {{result}}</p> </div> return factory;
<script src =
});
"https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js">
</script> mainApp.service('CalcService', function(MathService)
<script> {
var mainApp = angular.module("mainApp", []); this.square = function(a) {
return MathService.multiply(a,a);
mainApp.config(function($provide) {
} });
$provide.provider('MathService', function() { mainApp.controller('CalcController', function($scope,
this.$get = function() { CalcService, defaultInput) {
var factory = {}; $scope.number = defaultInput;
factory.multiply = function(a, b) {
return a * b; $scope.result = CalcService.square($scope.number);
}
$scope.square = function() {
return factory; $scope.result =
}; CalcService.square($scope.number);
}); } });
});
</script> </body></html>
AngularJS Services
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.
There are two ways to create a service −
• 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
• 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.
AngularJS Forms
AngularJS facilitates you to create a form enriches with 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.
Following are the input controls used in AngularJS forms:
• input elements
• select elements
• button elements
• textarea elements
Events
Usually 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
AngularJS Checkbox
A checkbox has a value true or false. The ng-model directive is used for a checkbox.
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>
<div ng-app="">
<form>
Check to show a header:
<input type="checkbox" ng-model="myVar">
</form>
<h1 ng-show="myVar">My Header</h1>
</div>
<p>The header's ng-show attribute is set to true when the checkbox is checked.</p>
</body>
</html>
AngularJS Radio Buttons
ng-model directive is used to bind radio buttons in your applications
<html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body ng-app="">
<div ng-switch-when="fest">
<form>
<h1>Festivals</h1>
Pick a topic: <p>Most famous festivals</p>
<input type="radio" ng-model="myVar" value="tuts">Tutorials </div>
<input type="radio" ng-model="myVar" value="fest">Festivals <div ng-switch-when="news">
<input type="radio" ng-model="myVar" value="news">News <h1>News</h1>
</form> <p>Welcome to the news portal.</p>
<div ng-switch="myVar">
</div>
</div>
<div ng-switch-when="tuts">
<p>The ng-
<h1>Tutorials</h1> switch directive hides and shows HTML secti
<p>Welcome to the best tutorials over the net</p> </div> ons depending on the value of the radio butto
ns.</p>
</div> </body>
</html>
Form Validation
AngularJS offers client-side form validation.
AngularJS monitors the state of the form and input fields (input, textarea, select), and lets
you notify the user about the current state.
AngularJS also holds information about whether they have been touched, or modified, or not.
You can use standard HTML5 attributes to validate input, or you can make your own
validation functions
Note: Client-side validation cannot alone secure user input. Server-side validation is also necessary.
<p>Email:<br>
<input type="email" name="email" ng-model="email" required>
<span style="color:red" ng-show="myForm.email.$dirty && myForm.email.$invalid">
<span ng-show="myForm.email.$error.required">Email is required.</span>
<span ng-show="myForm.email.$error.email">Invalid email address.</span>
</span>
</p>
If you want to navigate to different pages in your application, but you also want the
application to be a SPA (Single Page Application), with no page reloading, you can use
the ngRoute module.
The ngRoute module routes your application to different pages without reloading the
entire application
Step-1
Step -2
With the $routeProvider you can define what page to display when a user clicks a link
Step-3
Your application needs a container to put the content provided by the routing.
This container is the ng-view directive.
There are three different ways to include the ng-view directive in your application:
1. <div ng-view></div>
2. <ng-view></ng-view>
3. <div class="ng-view"></div>