SlideShare a Scribd company logo
Single Page
Applications
Workshop
Jalal Mostafa
Your first AngularJS
Application
Session 3
Single Page Applications
– Loads a single HTML page
– Dynamically update that page as
the user interacts with the app.
– Better User eXperience (UX)
– Better performance and fast page
load
– Some SPA frameworks: AngularJS –
Angular (evolution of AngularJS) –
Vue.js - ReactJS
3
AngularJS
– Adds new attributes to HTML5 to manipulate the webpage
– Application’s architecture is Model-View-Controller (MVC) design pattern
– Supports Asynchronous Programming and AJAX
AngularJS: HTML Extensions
– AngularJS extends HTML with new attributes called “directives”
– E.g.
– ng-app directive defines an AngularJS application
– ng-model directive binds the value of HTML controls (input, select, textarea) to
application data.
– ng-bind directive binds application data to the HTML view
– ….
AngularJS: HTML Extensions
<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>
First Name: <span ng-bind="firstName"></span><br>
Last Name: <span ng-bind="lastName"></span>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.firstName= "Computer";
$scope.lastName= "Science";
});
</script>
Demo on AngularJS
HTML Extensions
Session 3
AngularJS: MVC
– Model-View-Controller (MVC)
is a design pattern[1]
– Model structures data into
reliable representations
– View displays data to user
– Controller takes in user
commands, sends commands
to the model for data updates,
sends instructions to view to
update interface.
User
View
Controller
Model
Datab
ase
User Action/Input
Update
Update
Notify
AngularJS: MVC
<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>
First Name: <span ng-bind="firstName"></span><br>
Last Name: <span ng-bind="lastName"></span>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.firstName= "Computer";
$scope.lastName= "Science";
});
</script>
} View
}Model } Controller
Binding and Expressions
– Data binding is the synchronization
between the model and the view
– Two kinds of binding
– Two-Way Binding (ng-model)
– When view changes, it updates the
model
– When model changes, it updates the
model
– One-Way Binding (ng-bind and {{ expr
}} expressions)
– When model changes, it updates the
model
View Model
Two-Way Binding
View Model
One-Way Binding
Binding and Expressions
– Instead of using the directive ng-bind, you can also use double braces
expressions {{ expr }}
– AngularJS will resolve expr and replace it with its value
– AngularJS supports all JavaScript expressions
– A variable e.g. {{ var }}, {{ var1 + var2 }}, {{ var1 * var2 }}, {{ var1 + ‘ ’ + var2 }}
– A method calling e.g. {{ methodName() }}
– Object properties and methods e.g. {{ person.firstName }}, {{ person.fullName() }}
– Array Elements e.g. {{ array[0] }}, {{ array.includes(1) }}
– Ternary Operator e.g. {{myVar === "two" ? "it's true" : "it's false"}}
Controllers
– AngularJS controllers control the data of
AngularJS applications.
– ng-controller directive defines the
application controller for a part of the view
– The value of ng-controller is the name
assigned to the controller
<body ng-app="myApp">
<div ng-controller="myCtrl">
{{ firstName + " " + lastName }}
</div>
<script>
var app =
angular.module("myApp", []);
app.controller("myCtrl", function($
scope) {
$scope.firstName = “Computer";
$scope.lastName = “Science";
});
</script>
</body>
Scopes
– A scope[2] is the binding part between the HTML (view) and the JavaScript
(controller)
– When adding properties to the $scope object in the controller, the view (HTML)
gets access to these properties
– In the view, you do not use the prefix $scope
– Scope is the model
– $rootScope is the scope of the whole application.
– It is defined using ng-app
– It belongs to the element that has ng-app
Scopes
– A scope is the binding part between the HTML (view) and the JavaScript
(controller)
– When adding properties to the $scope object in the controller, the view (HTML)
gets access to these properties
– In the view, you do not use the prefix $scope
– Scope is the model
– $rootScope is the scope of the whole application.
– It is defined using ng-app, one and only one per app
– It belongs to the element that has ng-app
Scopes
– The application can have multiple scopes
– Directives can create new child scopes.
– When new scopes are created, they are added as children of their parent scope.
– If a property has not been found on the current scope, AngularJS search parent
scopes until it reaches the root scope $rootScope
– Directives that create scopes: ng-app, ng-controller, ng-repeat
Events
– Add AngularJS event listeners to
HTML elements by using directives
– E.g. <div ng-click=“onClick()”>
where onClick() is a to-be-defined
scope method
– Another use example is <div ng-
click=“onClick($event)”>
– $event is an object of some
data representing the event
passed by the browser
– ng-change fired on value changes
– ng-click fired on element click
– ng-copy fired on text copy
– ng-cut fired on text cut
– ng-dblclick fired on double click
– ng-focus fired on element focus
– ng-paste fired on text paste
– Mouse/Keyboard Events
Styling with AngularJS
– ng-show/ng-hide =“condition” show/hide an element if the condition was true
– ng-if =“condition” adds/removes an element from the DOM according to the
condition
– ng-switch=“expression” switch case on the expression
– ng-switch-when=“matchValue” if matchValue is equal to expression then the element
is outputted and added to the DOM
– ng-switch-default if no ng-switch-when matched the expression then the element of
ng-switch-default is outputted
Styling with AngularJS
– Ng-class=‘expression’, expression can be
– Object e.g. {strike: deleted, bold: important, 'has-error': error}, a class named ‘strike’ will be added to
the element if deleted is true…
– Array e.g. [style1, style2] and we can bind style1 and style2 to an element value
– Other expressions
<p ng-class="[style1, style2, style3]">Using Array Syntax</p>
<input ng-model="style1" placeholder="Type: bold, strike or red" aria-label="Type: bold,
strike or red"><br>
<input ng-model="style2" placeholder="Type: bold, strike or red" aria-label="Type: bold,
strike or red 2"><br>
<input ng-model="style3" placeholder="Type: bold, strike or red" aria-label="Type: bold,
strike or red 3"><br>
Styling with AngularJS
– Ng-style=‘expression’
– E.g. <span ng-style="{color:'red'}">Sample Text</span>
References
[1]: https://medium.freecodecamp.org/model-view-controller-mvc-explained-
through-ordering-drinks-at-the-bar-efcba6255053
[2]: https://code.angularjs.org/snapshot/docs/guide/scope
Live Coding: Your First
AngularJS Application
Session 3
More AngularJS: Services,
Filters and Routing
Session 4
$http: AJAX in AngularJS
– AngularJS supports AJAX requests by using $http service [1]
– $http is a built-in service of AngularJS that provide the functionality to send HTTP
requests and receive responses.
angular
.module('myApp', [])
.controller('MyController', function ($scope, $http) {
$scope.downloadData = function () {
$http.get('url').then(function () { });
};
});
$http: AJAX in AngularJS
– $http uses promises
(deferred objects) to
download asynchronously.
Use then, catch, and finally
to control the promise results
– The promise result is a
response object [2]
{
data: string | Object, // The response body
transformed with the transform functions.
status: number, // HTTP status code of the
response.
headers: function ([headerName]), // Header
getter function.
config: Object, // The configuration object
that was used to generate the request.
statusText: string, // HTTP status text of
the response.
xhrStatus: string, // Status of the
XMLHttpRequest(complete, error, timeout or
abort).
}
A Question about AngularJS
Services
angular
.module('myApp', [])
.controller('MyController',
function ($scope, $http){
$scope.downloadData =
function () {
$http.get('url').then(f
unction () { });
};
});
angular
.module('myApp', [])
.controller('MyController',
function ($http, $scope){
$scope.downloadData =
function () {
$http.get('url').then
(function () { });
};
});
Dependency Injection (DI)
– Dependency Injection (DI) is a design pattern that deals with how components get hold of their
dependencies.
– Without dependency injection, a developer has to mind configuring the dependencies of a software
component
– A developer might write codes of different jobs inside one component => prone to modifications and uneasy to read
– A developer has to initialize and configure dependencies by hand => More work, less value
– Goals
– Better Code Reusability
– How?
– No code has to be changed if you changed the code it depends on it. (Dependency Inversion Principle [3])
– Decoupling the usage of an object from its creation. A software component must do one thing and only thing
(Single Responsibility Principle [3])
DI in AngularJS
– AngularJS employs Dependency Injection by default to manage dependencies in controllers, directives, components, etc…
– It has built-in services that the developer can use e.g. $http and $scope
– By convention, built-in services’ names start with a $ sign
– No extra code or configuration is needed to use these services, just pass the default name to the controller function
– The developer can define his own services using angular.service and angular.factory
angular.module('myApp', []).
controller('MyController', ['$scope', '$http', 'service1', 'service2', function ($scope,
$http, service1, service2) {
$scope.downloadData = function () {
$http.get('url').then(function () {});
};
}]);
Custom Services
– Angular.service implements the
service pattern
– Break application into different
services, each service is
responsible for one thing
– Used for utilities e.g. $http, the
http requests service gives the
ability to send AJAX requests
– A service is an object
(instantiated using new)
angular.module('myApp', [])
.service('booksService', ['$http', function
($http) {
var baseUrl = 'http://localhost:3000';
this.getBooks = function () {
return $http.get(baseUrl +
'/books');
};
this.getBook = function(id) {
return $http.get(baseUrl +
'/books/' + id);
}
}]);
Factories
– Angular.factory implements the
factory pattern
– A factory function to generate an
object
– Returns a constructor of objects. The
constructor can be a function, a class
to instantiated with new, an object, a
string, a number
angular.module('myApp', [])
.factory('urlFactory',
function() {
var baseUrl =
'http://localhost:3000';
return function(url) {
return baseUrl + url;
};
});
Filters
– Filters format the value of an expression for display to the user
– can be used in view templates, controllers or services
– E.g {{ expression | filter1 | filter2:arg1:arg2 | ... }}
– Some built-in filters
– Filter selects a subset of items from array and returns it as a new array. Usecase: searching some elements
– Currency formats a number as a currency (ie $1,234.56)
– Number formats a number as text.
– Date formats date to a string based on the requested format.
– Json allows you to convert a JavaScript object into JSON string.
– Lowercase converts string to lowercase
– Uppercase converts string to uppercase.
– limitTo choose N elements from an array
– orderBy order a set of elements by a property
Routing
– An application may have multiple
views with their corresponding
controllers
– To switch between views, we use
routing
– Routing is used to bind URLs to
views, e.g. ‘/#!/favoriteBooks’ to a
specific HTML code
– We can ‘route’ between views using
an angular plugin called ngRoute,
npm package name angular-route
App
/
Books
/
BooksList
/
BookDetail
/books/id
Authors
/authors
AuthorsList
/authors
AuthorDetail
/authors/id
AuthorInsert
/authors/new
Using ngRoute
<script src="lib/angular-
route/angular-route.js"></script>
angular.module('myApp', [
'ngRoute',
...
]);
<div ng-view></div>
app.config(['$routeProvider',
function config($routeProvider)
{
$routeProvider
.when('/books', {templateUrl:
'books/list.html'})
.when('/authors/:authorId',
{templateUrl:
'authors/detail.html’})
.otherwise('/books');
}
]);
Using ngRoute
– To using routing parameters inside the
controller inject the $routeParam service
app.controller('MyController',
['$scope', '$http', '$routeParam',
function ($scope, $http,
$routeParam) {
var baseUrl =
'http://localhost:3000/';
$scope.downloadData = function
() {
$http.get(baseUrl +
'books/' + $routeParam.bookId
).then(function () {});
};
}]);
Project Directories and Files
Organization
– Put each entity in its own file.
– Each controller its own file
– Each service in its own file
– Organize our code by feature area,
instead of by function.
– Split your code into modules that
other modules can depend on.
– app/
– book-list/
– book-list.component.js
– book-list.template.html
– app.js
Project Directories and Files
Organization
– Split your code into modules that
other modules can depend on.
angular.module('bookList');
var app =
angular.module('myApp',
['bookList', 'ngRoute']);
– app/
– book-list/
– book-list.component.js
– book-list.template.html
– app.js
References
[1]: https://docs.angularjs.org/api/ng/service/$http
[2]: https://docs.angularjs.org/api/ng/service/$http#$http-returns
[3]: https://stackify.com/solid-design-principles/
Demo: Services, Filters,
and Routing
Session 4

More Related Content

What's hot (20)

Angular IO
Angular IOAngular IO
Angular IO
Jennifer Estrada
 
jQuery
jQueryjQuery
jQuery
Ivano Malavolta
 
Getting Started with jQuery
Getting Started with jQueryGetting Started with jQuery
Getting Started with jQuery
Akshay Mathur
 
Wt unit 5 client &amp; server side framework
Wt unit 5 client &amp; server side frameworkWt unit 5 client &amp; server side framework
Wt unit 5 client &amp; server side framework
PUNE VIDYARTHI GRIHA'S COLLEGE OF ENGINEERING, NASHIK
 
[2015/2016] Local data storage for web-based mobile apps
[2015/2016] Local data storage for web-based mobile apps[2015/2016] Local data storage for web-based mobile apps
[2015/2016] Local data storage for web-based mobile apps
Ivano Malavolta
 
Jasig Rubyon Rails
Jasig Rubyon RailsJasig Rubyon Rails
Jasig Rubyon Rails
Paul Pajo
 
Angular js for Beginnners
Angular js for BeginnnersAngular js for Beginnners
Angular js for Beginnners
Santosh Kumar Kar
 
An Introduction to Ruby on Rails
An Introduction to Ruby on RailsAn Introduction to Ruby on Rails
An Introduction to Ruby on Rails
Joe Fiorini
 
Backbone.js
Backbone.jsBackbone.js
Backbone.js
Ivano Malavolta
 
AngularJS Introduction
AngularJS IntroductionAngularJS Introduction
AngularJS Introduction
Brajesh Yadav
 
Controller in AngularJS
Controller in AngularJSController in AngularJS
Controller in AngularJS
Brajesh Yadav
 
Introduction to AngularJS By Bharat Makwana
Introduction to AngularJS By Bharat MakwanaIntroduction to AngularJS By Bharat Makwana
Introduction to AngularJS By Bharat Makwana
Bharat Makwana
 
Building AngularJS Custom Directives
Building AngularJS Custom DirectivesBuilding AngularJS Custom Directives
Building AngularJS Custom Directives
Dan Wahlin
 
Rest
Rest Rest
Rest
Ivano Malavolta
 
jQuery - Chapter 3 - Effects
jQuery - Chapter 3 - Effects  jQuery - Chapter 3 - Effects
jQuery - Chapter 3 - Effects
WebStackAcademy
 
Handlebars & Require JS
Handlebars  & Require JSHandlebars  & Require JS
Handlebars & Require JS
Ivano Malavolta
 
Ruby On Rails
Ruby On RailsRuby On Rails
Ruby On Rails
Balint Erdi
 
JavaScript
JavaScriptJavaScript
JavaScript
Ivano Malavolta
 
Shaping up with angular JS
Shaping up with angular JSShaping up with angular JS
Shaping up with angular JS
Brajesh Yadav
 
Templates
TemplatesTemplates
Templates
soon
 

Similar to Single Page Applications Workshop Part II: Single Page Applications using AngularJS (20)

Basics of AngularJS
Basics of AngularJSBasics of AngularJS
Basics of AngularJS
Filip Janevski
 
Angular workshop - Full Development Guide
Angular workshop - Full Development GuideAngular workshop - Full Development Guide
Angular workshop - Full Development Guide
Nitin Giri
 
Intro to AngularJs
Intro to AngularJsIntro to AngularJs
Intro to AngularJs
SolTech, Inc.
 
One Weekend With AngularJS
One Weekend With AngularJSOne Weekend With AngularJS
One Weekend With AngularJS
Yashobanta Bai
 
AngularJS: Overview & Key Features
AngularJS: Overview & Key FeaturesAngularJS: Overview & Key Features
AngularJS: Overview & Key Features
Mohamad Al Asmar
 
Angular js
Angular jsAngular js
Angular js
Arun Somu Panneerselvam
 
AngularJS Workshop
AngularJS WorkshopAngularJS Workshop
AngularJS Workshop
Gianluca Cacace
 
Everything You Need To Know About AngularJS
Everything You Need To Know About AngularJSEverything You Need To Know About AngularJS
Everything You Need To Know About AngularJS
Sina Mirhejazi
 
Angular js
Angular jsAngular js
Angular js
yogi_solanki
 
Angular js
Angular jsAngular js
Angular js
Silver Touch Technologies Ltd
 
Angular Presentation
Angular PresentationAngular Presentation
Angular Presentation
Adam Moore
 
Angularjs
AngularjsAngularjs
Angularjs
Sabin Tamrakar
 
AngularJS Basics
AngularJS BasicsAngularJS Basics
AngularJS Basics
Ravi Mone
 
Learning AngularJS - Complete coverage of AngularJS features and concepts
Learning AngularJS  - Complete coverage of AngularJS features and conceptsLearning AngularJS  - Complete coverage of AngularJS features and concepts
Learning AngularJS - Complete coverage of AngularJS features and concepts
Suresh Patidar
 
Angular js
Angular jsAngular js
Angular js
Hritesh Saha
 
Intoduction to Angularjs
Intoduction to AngularjsIntoduction to Angularjs
Intoduction to Angularjs
Gaurav Agrawal
 
Introduction to AngularJs
Introduction to AngularJsIntroduction to AngularJs
Introduction to AngularJs
murtazahaveliwala
 
Understanding angular js
Understanding angular jsUnderstanding angular js
Understanding angular js
Aayush Shrestha
 
Practical AngularJS
Practical AngularJSPractical AngularJS
Practical AngularJS
Wei Ru
 
introduction to Angularjs basics
introduction to Angularjs basicsintroduction to Angularjs basics
introduction to Angularjs basics
Ravindra K
 
Angular workshop - Full Development Guide
Angular workshop - Full Development GuideAngular workshop - Full Development Guide
Angular workshop - Full Development Guide
Nitin Giri
 
One Weekend With AngularJS
One Weekend With AngularJSOne Weekend With AngularJS
One Weekend With AngularJS
Yashobanta Bai
 
AngularJS: Overview & Key Features
AngularJS: Overview & Key FeaturesAngularJS: Overview & Key Features
AngularJS: Overview & Key Features
Mohamad Al Asmar
 
Everything You Need To Know About AngularJS
Everything You Need To Know About AngularJSEverything You Need To Know About AngularJS
Everything You Need To Know About AngularJS
Sina Mirhejazi
 
Angular Presentation
Angular PresentationAngular Presentation
Angular Presentation
Adam Moore
 
AngularJS Basics
AngularJS BasicsAngularJS Basics
AngularJS Basics
Ravi Mone
 
Learning AngularJS - Complete coverage of AngularJS features and concepts
Learning AngularJS  - Complete coverage of AngularJS features and conceptsLearning AngularJS  - Complete coverage of AngularJS features and concepts
Learning AngularJS - Complete coverage of AngularJS features and concepts
Suresh Patidar
 
Intoduction to Angularjs
Intoduction to AngularjsIntoduction to Angularjs
Intoduction to Angularjs
Gaurav Agrawal
 
Understanding angular js
Understanding angular jsUnderstanding angular js
Understanding angular js
Aayush Shrestha
 
Practical AngularJS
Practical AngularJSPractical AngularJS
Practical AngularJS
Wei Ru
 
introduction to Angularjs basics
introduction to Angularjs basicsintroduction to Angularjs basics
introduction to Angularjs basics
Ravindra K
 
Ad

Recently uploaded (20)

Design by Contract - Building Robust Software with Contract-First Development
Design by Contract - Building Robust Software with Contract-First DevelopmentDesign by Contract - Building Robust Software with Contract-First Development
Design by Contract - Building Robust Software with Contract-First Development
Par-Tec S.p.A.
 
Content Mate Web App Triples Content Managers‘ Productivity
Content Mate Web App Triples Content Managers‘ ProductivityContent Mate Web App Triples Content Managers‘ Productivity
Content Mate Web App Triples Content Managers‘ Productivity
Alex Vladimirovich
 
BoxLang-Dynamic-AWS-Lambda by Luis Majano.pdf
BoxLang-Dynamic-AWS-Lambda by Luis Majano.pdfBoxLang-Dynamic-AWS-Lambda by Luis Majano.pdf
BoxLang-Dynamic-AWS-Lambda by Luis Majano.pdf
Ortus Solutions, Corp
 
aswjkdwelhjdfshlfjkhewljhfljawerhwjarhwjkahrjar
aswjkdwelhjdfshlfjkhewljhfljawerhwjarhwjkahrjaraswjkdwelhjdfshlfjkhewljhfljawerhwjarhwjkahrjar
aswjkdwelhjdfshlfjkhewljhfljawerhwjarhwjkahrjar
muhammadalikhanalikh1
 
Rebuilding Cadabra Studio: AI as Our Core Foundation
Rebuilding Cadabra Studio: AI as Our Core FoundationRebuilding Cadabra Studio: AI as Our Core Foundation
Rebuilding Cadabra Studio: AI as Our Core Foundation
Cadabra Studio
 
zOS CommServer support for the Network Express feature on z17
zOS CommServer support for the Network Express feature on z17zOS CommServer support for the Network Express feature on z17
zOS CommServer support for the Network Express feature on z17
zOSCommserver
 
grade 9 ai project cycle Artificial intelligence.pptx
grade 9 ai project cycle Artificial intelligence.pptxgrade 9 ai project cycle Artificial intelligence.pptx
grade 9 ai project cycle Artificial intelligence.pptx
manikumar465287
 
Boost Student Engagement with Smart Attendance Software for Schools
Boost Student Engagement with Smart Attendance Software for SchoolsBoost Student Engagement with Smart Attendance Software for Schools
Boost Student Engagement with Smart Attendance Software for Schools
Visitu
 
AI Alternative - Discover the best AI tools and their alternatives
AI Alternative - Discover the best AI tools and their alternativesAI Alternative - Discover the best AI tools and their alternatives
AI Alternative - Discover the best AI tools and their alternatives
AI Alternative
 
How to Generate Financial Statements in QuickBooks Like a Pro (1).pdf
How to Generate Financial Statements in QuickBooks Like a Pro (1).pdfHow to Generate Financial Statements in QuickBooks Like a Pro (1).pdf
How to Generate Financial Statements in QuickBooks Like a Pro (1).pdf
QuickBooks Training
 
iOS Developer Resume 2025 | Pramod Kumar
iOS Developer Resume 2025 | Pramod KumariOS Developer Resume 2025 | Pramod Kumar
iOS Developer Resume 2025 | Pramod Kumar
Pramod Kumar
 
ICDL FULL STANDARD 2025 Luisetto mauro - Academia domani- 55 HOURS LONG pdf
ICDL FULL STANDARD  2025 Luisetto mauro - Academia domani- 55 HOURS LONG pdfICDL FULL STANDARD  2025 Luisetto mauro - Academia domani- 55 HOURS LONG pdf
ICDL FULL STANDARD 2025 Luisetto mauro - Academia domani- 55 HOURS LONG pdf
M. Luisetto Pharm.D.Spec. Pharmacology
 
GirikHire Unlocking the Future of Tech Talent with AI-Powered Hiring Solution...
GirikHire Unlocking the Future of Tech Talent with AI-Powered Hiring Solution...GirikHire Unlocking the Future of Tech Talent with AI-Powered Hiring Solution...
GirikHire Unlocking the Future of Tech Talent with AI-Powered Hiring Solution...
GirikHire
 
Topic 26 Security Testing Considerations.pptx
Topic 26 Security Testing Considerations.pptxTopic 26 Security Testing Considerations.pptx
Topic 26 Security Testing Considerations.pptx
marutnand8
 
Build enterprise-ready applications using skills you already have!
Build enterprise-ready applications using skills you already have!Build enterprise-ready applications using skills you already have!
Build enterprise-ready applications using skills you already have!
PhilMeredith3
 
Autoposting.ai Sales Deck - Skyrocket your LinkedIn's ROI
Autoposting.ai Sales Deck - Skyrocket your LinkedIn's ROIAutoposting.ai Sales Deck - Skyrocket your LinkedIn's ROI
Autoposting.ai Sales Deck - Skyrocket your LinkedIn's ROI
Udit Goenka
 
The rise of e-commerce has redefined how retailers operate—and reconciliation...
The rise of e-commerce has redefined how retailers operate—and reconciliation...The rise of e-commerce has redefined how retailers operate—and reconciliation...
The rise of e-commerce has redefined how retailers operate—and reconciliation...
Prachi Desai
 
Internship in South western railways on software
Internship in South western railways on softwareInternship in South western railways on software
Internship in South western railways on software
abhim5889
 
Oliveira2024 - Combining GPT and Weak Supervision.pdf
Oliveira2024 - Combining GPT and Weak Supervision.pdfOliveira2024 - Combining GPT and Weak Supervision.pdf
Oliveira2024 - Combining GPT and Weak Supervision.pdf
GiliardGodoi1
 
Micro-Metrics Every Performance Engineer Should Validate Before Sign-Off
Micro-Metrics Every Performance Engineer Should Validate Before Sign-OffMicro-Metrics Every Performance Engineer Should Validate Before Sign-Off
Micro-Metrics Every Performance Engineer Should Validate Before Sign-Off
Tier1 app
 
Design by Contract - Building Robust Software with Contract-First Development
Design by Contract - Building Robust Software with Contract-First DevelopmentDesign by Contract - Building Robust Software with Contract-First Development
Design by Contract - Building Robust Software with Contract-First Development
Par-Tec S.p.A.
 
Content Mate Web App Triples Content Managers‘ Productivity
Content Mate Web App Triples Content Managers‘ ProductivityContent Mate Web App Triples Content Managers‘ Productivity
Content Mate Web App Triples Content Managers‘ Productivity
Alex Vladimirovich
 
BoxLang-Dynamic-AWS-Lambda by Luis Majano.pdf
BoxLang-Dynamic-AWS-Lambda by Luis Majano.pdfBoxLang-Dynamic-AWS-Lambda by Luis Majano.pdf
BoxLang-Dynamic-AWS-Lambda by Luis Majano.pdf
Ortus Solutions, Corp
 
aswjkdwelhjdfshlfjkhewljhfljawerhwjarhwjkahrjar
aswjkdwelhjdfshlfjkhewljhfljawerhwjarhwjkahrjaraswjkdwelhjdfshlfjkhewljhfljawerhwjarhwjkahrjar
aswjkdwelhjdfshlfjkhewljhfljawerhwjarhwjkahrjar
muhammadalikhanalikh1
 
Rebuilding Cadabra Studio: AI as Our Core Foundation
Rebuilding Cadabra Studio: AI as Our Core FoundationRebuilding Cadabra Studio: AI as Our Core Foundation
Rebuilding Cadabra Studio: AI as Our Core Foundation
Cadabra Studio
 
zOS CommServer support for the Network Express feature on z17
zOS CommServer support for the Network Express feature on z17zOS CommServer support for the Network Express feature on z17
zOS CommServer support for the Network Express feature on z17
zOSCommserver
 
grade 9 ai project cycle Artificial intelligence.pptx
grade 9 ai project cycle Artificial intelligence.pptxgrade 9 ai project cycle Artificial intelligence.pptx
grade 9 ai project cycle Artificial intelligence.pptx
manikumar465287
 
Boost Student Engagement with Smart Attendance Software for Schools
Boost Student Engagement with Smart Attendance Software for SchoolsBoost Student Engagement with Smart Attendance Software for Schools
Boost Student Engagement with Smart Attendance Software for Schools
Visitu
 
AI Alternative - Discover the best AI tools and their alternatives
AI Alternative - Discover the best AI tools and their alternativesAI Alternative - Discover the best AI tools and their alternatives
AI Alternative - Discover the best AI tools and their alternatives
AI Alternative
 
How to Generate Financial Statements in QuickBooks Like a Pro (1).pdf
How to Generate Financial Statements in QuickBooks Like a Pro (1).pdfHow to Generate Financial Statements in QuickBooks Like a Pro (1).pdf
How to Generate Financial Statements in QuickBooks Like a Pro (1).pdf
QuickBooks Training
 
iOS Developer Resume 2025 | Pramod Kumar
iOS Developer Resume 2025 | Pramod KumariOS Developer Resume 2025 | Pramod Kumar
iOS Developer Resume 2025 | Pramod Kumar
Pramod Kumar
 
ICDL FULL STANDARD 2025 Luisetto mauro - Academia domani- 55 HOURS LONG pdf
ICDL FULL STANDARD  2025 Luisetto mauro - Academia domani- 55 HOURS LONG pdfICDL FULL STANDARD  2025 Luisetto mauro - Academia domani- 55 HOURS LONG pdf
ICDL FULL STANDARD 2025 Luisetto mauro - Academia domani- 55 HOURS LONG pdf
M. Luisetto Pharm.D.Spec. Pharmacology
 
GirikHire Unlocking the Future of Tech Talent with AI-Powered Hiring Solution...
GirikHire Unlocking the Future of Tech Talent with AI-Powered Hiring Solution...GirikHire Unlocking the Future of Tech Talent with AI-Powered Hiring Solution...
GirikHire Unlocking the Future of Tech Talent with AI-Powered Hiring Solution...
GirikHire
 
Topic 26 Security Testing Considerations.pptx
Topic 26 Security Testing Considerations.pptxTopic 26 Security Testing Considerations.pptx
Topic 26 Security Testing Considerations.pptx
marutnand8
 
Build enterprise-ready applications using skills you already have!
Build enterprise-ready applications using skills you already have!Build enterprise-ready applications using skills you already have!
Build enterprise-ready applications using skills you already have!
PhilMeredith3
 
Autoposting.ai Sales Deck - Skyrocket your LinkedIn's ROI
Autoposting.ai Sales Deck - Skyrocket your LinkedIn's ROIAutoposting.ai Sales Deck - Skyrocket your LinkedIn's ROI
Autoposting.ai Sales Deck - Skyrocket your LinkedIn's ROI
Udit Goenka
 
The rise of e-commerce has redefined how retailers operate—and reconciliation...
The rise of e-commerce has redefined how retailers operate—and reconciliation...The rise of e-commerce has redefined how retailers operate—and reconciliation...
The rise of e-commerce has redefined how retailers operate—and reconciliation...
Prachi Desai
 
Internship in South western railways on software
Internship in South western railways on softwareInternship in South western railways on software
Internship in South western railways on software
abhim5889
 
Oliveira2024 - Combining GPT and Weak Supervision.pdf
Oliveira2024 - Combining GPT and Weak Supervision.pdfOliveira2024 - Combining GPT and Weak Supervision.pdf
Oliveira2024 - Combining GPT and Weak Supervision.pdf
GiliardGodoi1
 
Micro-Metrics Every Performance Engineer Should Validate Before Sign-Off
Micro-Metrics Every Performance Engineer Should Validate Before Sign-OffMicro-Metrics Every Performance Engineer Should Validate Before Sign-Off
Micro-Metrics Every Performance Engineer Should Validate Before Sign-Off
Tier1 app
 
Ad

Single Page Applications Workshop Part II: Single Page Applications using AngularJS

  • 3. Single Page Applications – Loads a single HTML page – Dynamically update that page as the user interacts with the app. – Better User eXperience (UX) – Better performance and fast page load – Some SPA frameworks: AngularJS – Angular (evolution of AngularJS) – Vue.js - ReactJS 3
  • 4. AngularJS – Adds new attributes to HTML5 to manipulate the webpage – Application’s architecture is Model-View-Controller (MVC) design pattern – Supports Asynchronous Programming and AJAX
  • 5. AngularJS: HTML Extensions – AngularJS extends HTML with new attributes called “directives” – E.g. – ng-app directive defines an AngularJS application – ng-model directive binds the value of HTML controls (input, select, textarea) to application data. – ng-bind directive binds application data to the HTML view – ….
  • 6. AngularJS: HTML Extensions <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> First Name: <span ng-bind="firstName"></span><br> Last Name: <span ng-bind="lastName"></span> </div> <script> var app = angular.module('myApp', []); app.controller('myCtrl', function($scope) { $scope.firstName= "Computer"; $scope.lastName= "Science"; }); </script>
  • 7. Demo on AngularJS HTML Extensions Session 3
  • 8. AngularJS: MVC – Model-View-Controller (MVC) is a design pattern[1] – Model structures data into reliable representations – View displays data to user – Controller takes in user commands, sends commands to the model for data updates, sends instructions to view to update interface. User View Controller Model Datab ase User Action/Input Update Update Notify
  • 9. AngularJS: MVC <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> First Name: <span ng-bind="firstName"></span><br> Last Name: <span ng-bind="lastName"></span> </div> <script> var app = angular.module('myApp', []); app.controller('myCtrl', function($scope) { $scope.firstName= "Computer"; $scope.lastName= "Science"; }); </script> } View }Model } Controller
  • 10. Binding and Expressions – Data binding is the synchronization between the model and the view – Two kinds of binding – Two-Way Binding (ng-model) – When view changes, it updates the model – When model changes, it updates the model – One-Way Binding (ng-bind and {{ expr }} expressions) – When model changes, it updates the model View Model Two-Way Binding View Model One-Way Binding
  • 11. Binding and Expressions – Instead of using the directive ng-bind, you can also use double braces expressions {{ expr }} – AngularJS will resolve expr and replace it with its value – AngularJS supports all JavaScript expressions – A variable e.g. {{ var }}, {{ var1 + var2 }}, {{ var1 * var2 }}, {{ var1 + ‘ ’ + var2 }} – A method calling e.g. {{ methodName() }} – Object properties and methods e.g. {{ person.firstName }}, {{ person.fullName() }} – Array Elements e.g. {{ array[0] }}, {{ array.includes(1) }} – Ternary Operator e.g. {{myVar === "two" ? "it's true" : "it's false"}}
  • 12. Controllers – AngularJS controllers control the data of AngularJS applications. – ng-controller directive defines the application controller for a part of the view – The value of ng-controller is the name assigned to the controller <body ng-app="myApp"> <div ng-controller="myCtrl"> {{ firstName + " " + lastName }} </div> <script> var app = angular.module("myApp", []); app.controller("myCtrl", function($ scope) { $scope.firstName = “Computer"; $scope.lastName = “Science"; }); </script> </body>
  • 13. Scopes – A scope[2] is the binding part between the HTML (view) and the JavaScript (controller) – When adding properties to the $scope object in the controller, the view (HTML) gets access to these properties – In the view, you do not use the prefix $scope – Scope is the model – $rootScope is the scope of the whole application. – It is defined using ng-app – It belongs to the element that has ng-app
  • 14. Scopes – A scope is the binding part between the HTML (view) and the JavaScript (controller) – When adding properties to the $scope object in the controller, the view (HTML) gets access to these properties – In the view, you do not use the prefix $scope – Scope is the model – $rootScope is the scope of the whole application. – It is defined using ng-app, one and only one per app – It belongs to the element that has ng-app
  • 15. Scopes – The application can have multiple scopes – Directives can create new child scopes. – When new scopes are created, they are added as children of their parent scope. – If a property has not been found on the current scope, AngularJS search parent scopes until it reaches the root scope $rootScope – Directives that create scopes: ng-app, ng-controller, ng-repeat
  • 16. Events – Add AngularJS event listeners to HTML elements by using directives – E.g. <div ng-click=“onClick()”> where onClick() is a to-be-defined scope method – Another use example is <div ng- click=“onClick($event)”> – $event is an object of some data representing the event passed by the browser – ng-change fired on value changes – ng-click fired on element click – ng-copy fired on text copy – ng-cut fired on text cut – ng-dblclick fired on double click – ng-focus fired on element focus – ng-paste fired on text paste – Mouse/Keyboard Events
  • 17. Styling with AngularJS – ng-show/ng-hide =“condition” show/hide an element if the condition was true – ng-if =“condition” adds/removes an element from the DOM according to the condition – ng-switch=“expression” switch case on the expression – ng-switch-when=“matchValue” if matchValue is equal to expression then the element is outputted and added to the DOM – ng-switch-default if no ng-switch-when matched the expression then the element of ng-switch-default is outputted
  • 18. Styling with AngularJS – Ng-class=‘expression’, expression can be – Object e.g. {strike: deleted, bold: important, 'has-error': error}, a class named ‘strike’ will be added to the element if deleted is true… – Array e.g. [style1, style2] and we can bind style1 and style2 to an element value – Other expressions <p ng-class="[style1, style2, style3]">Using Array Syntax</p> <input ng-model="style1" placeholder="Type: bold, strike or red" aria-label="Type: bold, strike or red"><br> <input ng-model="style2" placeholder="Type: bold, strike or red" aria-label="Type: bold, strike or red 2"><br> <input ng-model="style3" placeholder="Type: bold, strike or red" aria-label="Type: bold, strike or red 3"><br>
  • 19. Styling with AngularJS – Ng-style=‘expression’ – E.g. <span ng-style="{color:'red'}">Sample Text</span>
  • 21. Live Coding: Your First AngularJS Application Session 3
  • 22. More AngularJS: Services, Filters and Routing Session 4
  • 23. $http: AJAX in AngularJS – AngularJS supports AJAX requests by using $http service [1] – $http is a built-in service of AngularJS that provide the functionality to send HTTP requests and receive responses. angular .module('myApp', []) .controller('MyController', function ($scope, $http) { $scope.downloadData = function () { $http.get('url').then(function () { }); }; });
  • 24. $http: AJAX in AngularJS – $http uses promises (deferred objects) to download asynchronously. Use then, catch, and finally to control the promise results – The promise result is a response object [2] { data: string | Object, // The response body transformed with the transform functions. status: number, // HTTP status code of the response. headers: function ([headerName]), // Header getter function. config: Object, // The configuration object that was used to generate the request. statusText: string, // HTTP status text of the response. xhrStatus: string, // Status of the XMLHttpRequest(complete, error, timeout or abort). }
  • 25. A Question about AngularJS Services angular .module('myApp', []) .controller('MyController', function ($scope, $http){ $scope.downloadData = function () { $http.get('url').then(f unction () { }); }; }); angular .module('myApp', []) .controller('MyController', function ($http, $scope){ $scope.downloadData = function () { $http.get('url').then (function () { }); }; });
  • 26. Dependency Injection (DI) – Dependency Injection (DI) is a design pattern that deals with how components get hold of their dependencies. – Without dependency injection, a developer has to mind configuring the dependencies of a software component – A developer might write codes of different jobs inside one component => prone to modifications and uneasy to read – A developer has to initialize and configure dependencies by hand => More work, less value – Goals – Better Code Reusability – How? – No code has to be changed if you changed the code it depends on it. (Dependency Inversion Principle [3]) – Decoupling the usage of an object from its creation. A software component must do one thing and only thing (Single Responsibility Principle [3])
  • 27. DI in AngularJS – AngularJS employs Dependency Injection by default to manage dependencies in controllers, directives, components, etc… – It has built-in services that the developer can use e.g. $http and $scope – By convention, built-in services’ names start with a $ sign – No extra code or configuration is needed to use these services, just pass the default name to the controller function – The developer can define his own services using angular.service and angular.factory angular.module('myApp', []). controller('MyController', ['$scope', '$http', 'service1', 'service2', function ($scope, $http, service1, service2) { $scope.downloadData = function () { $http.get('url').then(function () {}); }; }]);
  • 28. Custom Services – Angular.service implements the service pattern – Break application into different services, each service is responsible for one thing – Used for utilities e.g. $http, the http requests service gives the ability to send AJAX requests – A service is an object (instantiated using new) angular.module('myApp', []) .service('booksService', ['$http', function ($http) { var baseUrl = 'http://localhost:3000'; this.getBooks = function () { return $http.get(baseUrl + '/books'); }; this.getBook = function(id) { return $http.get(baseUrl + '/books/' + id); } }]);
  • 29. Factories – Angular.factory implements the factory pattern – A factory function to generate an object – Returns a constructor of objects. The constructor can be a function, a class to instantiated with new, an object, a string, a number angular.module('myApp', []) .factory('urlFactory', function() { var baseUrl = 'http://localhost:3000'; return function(url) { return baseUrl + url; }; });
  • 30. Filters – Filters format the value of an expression for display to the user – can be used in view templates, controllers or services – E.g {{ expression | filter1 | filter2:arg1:arg2 | ... }} – Some built-in filters – Filter selects a subset of items from array and returns it as a new array. Usecase: searching some elements – Currency formats a number as a currency (ie $1,234.56) – Number formats a number as text. – Date formats date to a string based on the requested format. – Json allows you to convert a JavaScript object into JSON string. – Lowercase converts string to lowercase – Uppercase converts string to uppercase. – limitTo choose N elements from an array – orderBy order a set of elements by a property
  • 31. Routing – An application may have multiple views with their corresponding controllers – To switch between views, we use routing – Routing is used to bind URLs to views, e.g. ‘/#!/favoriteBooks’ to a specific HTML code – We can ‘route’ between views using an angular plugin called ngRoute, npm package name angular-route App / Books / BooksList / BookDetail /books/id Authors /authors AuthorsList /authors AuthorDetail /authors/id AuthorInsert /authors/new
  • 32. Using ngRoute <script src="lib/angular- route/angular-route.js"></script> angular.module('myApp', [ 'ngRoute', ... ]); <div ng-view></div> app.config(['$routeProvider', function config($routeProvider) { $routeProvider .when('/books', {templateUrl: 'books/list.html'}) .when('/authors/:authorId', {templateUrl: 'authors/detail.html’}) .otherwise('/books'); } ]);
  • 33. Using ngRoute – To using routing parameters inside the controller inject the $routeParam service app.controller('MyController', ['$scope', '$http', '$routeParam', function ($scope, $http, $routeParam) { var baseUrl = 'http://localhost:3000/'; $scope.downloadData = function () { $http.get(baseUrl + 'books/' + $routeParam.bookId ).then(function () {}); }; }]);
  • 34. Project Directories and Files Organization – Put each entity in its own file. – Each controller its own file – Each service in its own file – Organize our code by feature area, instead of by function. – Split your code into modules that other modules can depend on. – app/ – book-list/ – book-list.component.js – book-list.template.html – app.js
  • 35. Project Directories and Files Organization – Split your code into modules that other modules can depend on. angular.module('bookList'); var app = angular.module('myApp', ['bookList', 'ngRoute']); – app/ – book-list/ – book-list.component.js – book-list.template.html – app.js
  • 37. Demo: Services, Filters, and Routing Session 4

Editor's Notes

  • #4: User Experience (UX) refers to a person's emotions and attitudes about using a particular product, system or service.