SlideShare a Scribd company logo
1 of 37
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

What's hot (20)

Angular IO
Angular IOAngular IO
Angular IO
 
jQuery
jQueryjQuery
jQuery
 
Getting Started with jQuery
Getting Started with jQueryGetting Started with jQuery
Getting Started with jQuery
 
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
 
[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
 
Jasig Rubyon Rails
Jasig Rubyon RailsJasig Rubyon Rails
Jasig Rubyon Rails
 
Angular js for Beginnners
Angular js for BeginnnersAngular js for Beginnners
Angular js for Beginnners
 
An Introduction to Ruby on Rails
An Introduction to Ruby on RailsAn Introduction to Ruby on Rails
An Introduction to Ruby on Rails
 
Backbone.js
Backbone.jsBackbone.js
Backbone.js
 
AngularJS Introduction
AngularJS IntroductionAngularJS Introduction
AngularJS Introduction
 
Controller in AngularJS
Controller in AngularJSController in AngularJS
Controller in AngularJS
 
Introduction to AngularJS By Bharat Makwana
Introduction to AngularJS By Bharat MakwanaIntroduction to AngularJS By Bharat Makwana
Introduction to AngularJS By Bharat Makwana
 
Building AngularJS Custom Directives
Building AngularJS Custom DirectivesBuilding AngularJS Custom Directives
Building AngularJS Custom Directives
 
Rest
Rest Rest
Rest
 
jQuery - Chapter 3 - Effects
jQuery - Chapter 3 - Effects  jQuery - Chapter 3 - Effects
jQuery - Chapter 3 - Effects
 
Handlebars & Require JS
Handlebars  & Require JSHandlebars  & Require JS
Handlebars & Require JS
 
Ruby On Rails
Ruby On RailsRuby On Rails
Ruby On Rails
 
JavaScript
JavaScriptJavaScript
JavaScript
 
Shaping up with angular JS
Shaping up with angular JSShaping up with angular JS
Shaping up with angular JS
 
Templates
TemplatesTemplates
Templates
 

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

Angular Js Get Started - Complete Course
Angular Js Get Started - Complete CourseAngular Js Get Started - Complete Course
Angular Js Get Started - Complete CourseEPAM Systems
 
Angular Presentation
Angular PresentationAngular Presentation
Angular PresentationAdam Moore
 
AngularJs Superheroic JavaScript MVW Framework Services by Miracle Studios
AngularJs Superheroic JavaScript MVW Framework Services by Miracle StudiosAngularJs Superheroic JavaScript MVW Framework Services by Miracle Studios
AngularJs Superheroic JavaScript MVW Framework Services by Miracle StudiosLearnimtactics
 
One Weekend With AngularJS
One Weekend With AngularJSOne Weekend With AngularJS
One Weekend With AngularJSYashobanta Bai
 
AngularJS training - Day 1 - Basics: Why, What and basic features of AngularJS
AngularJS training - Day 1 - Basics: Why, What and basic features of AngularJSAngularJS training - Day 1 - Basics: Why, What and basic features of AngularJS
AngularJS training - Day 1 - Basics: Why, What and basic features of AngularJSmurtazahaveliwala
 
Understanding angular js
Understanding angular jsUnderstanding angular js
Understanding angular jsAayush Shrestha
 
AngularJS Basics
AngularJS BasicsAngularJS Basics
AngularJS BasicsRavi Mone
 
Intoduction to Angularjs
Intoduction to AngularjsIntoduction to Angularjs
Intoduction to AngularjsGaurav Agrawal
 
Angular1x and Angular 2 for Beginners
Angular1x and Angular 2 for BeginnersAngular1x and Angular 2 for Beginners
Angular1x and Angular 2 for BeginnersOswald Campesato
 
AngularJS 101 - Everything you need to know to get started
AngularJS 101 - Everything you need to know to get startedAngularJS 101 - Everything you need to know to get started
AngularJS 101 - Everything you need to know to get startedStéphane Bégaudeau
 

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

Angular Js Get Started - Complete Course
Angular Js Get Started - Complete CourseAngular Js Get Started - Complete Course
Angular Js Get Started - Complete Course
 
Angular Presentation
Angular PresentationAngular Presentation
Angular Presentation
 
AngularJs Superheroic JavaScript MVW Framework Services by Miracle Studios
AngularJs Superheroic JavaScript MVW Framework Services by Miracle StudiosAngularJs Superheroic JavaScript MVW Framework Services by Miracle Studios
AngularJs Superheroic JavaScript MVW Framework Services by Miracle Studios
 
Custom directive and scopes
Custom directive and scopesCustom directive and scopes
Custom directive and scopes
 
One Weekend With AngularJS
One Weekend With AngularJSOne Weekend With AngularJS
One Weekend With AngularJS
 
Angular js
Angular jsAngular js
Angular js
 
Basics of AngularJS
Basics of AngularJSBasics of AngularJS
Basics of AngularJS
 
AngularJS training - Day 1 - Basics: Why, What and basic features of AngularJS
AngularJS training - Day 1 - Basics: Why, What and basic features of AngularJSAngularJS training - Day 1 - Basics: Why, What and basic features of AngularJS
AngularJS training - Day 1 - Basics: Why, What and basic features of AngularJS
 
Angular js
Angular jsAngular js
Angular js
 
AngularJS.part1
AngularJS.part1AngularJS.part1
AngularJS.part1
 
Understanding angular js
Understanding angular jsUnderstanding angular js
Understanding angular js
 
Angular js
Angular jsAngular js
Angular js
 
AngularJS
AngularJSAngularJS
AngularJS
 
AngularJS Basics
AngularJS BasicsAngularJS Basics
AngularJS Basics
 
Angular js
Angular jsAngular js
Angular js
 
Angular js-crash-course
Angular js-crash-courseAngular js-crash-course
Angular js-crash-course
 
AngularJs
AngularJsAngularJs
AngularJs
 
Intoduction to Angularjs
Intoduction to AngularjsIntoduction to Angularjs
Intoduction to Angularjs
 
Angular1x and Angular 2 for Beginners
Angular1x and Angular 2 for BeginnersAngular1x and Angular 2 for Beginners
Angular1x and Angular 2 for Beginners
 
AngularJS 101 - Everything you need to know to get started
AngularJS 101 - Everything you need to know to get startedAngularJS 101 - Everything you need to know to get started
AngularJS 101 - Everything you need to know to get started
 

Recently uploaded

Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...stazi3110
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Modelsaagamshah0812
 
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfkalichargn70th171
 
Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...aditisharan08
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about usDynamic Netsoft
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxComplianceQuest1
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfkalichargn70th171
 
Engage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyEngage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyFrank van der Linden
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfjoe51371421
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptkotipi9215
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number SystemsJheuzeDellosa
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...soniya singh
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityNeo4j
 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - InfographicHr365.us smith
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...Christina Lin
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideChristina Lin
 

Recently uploaded (20)

Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
 
Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about us
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
Engage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyEngage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The Ugly
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdf
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.ppt
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number Systems
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered Sustainability
 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - Infographic
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
 

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

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