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

PPTX
Single Page Applications Workshop Part I: Interesting Topics in HTML5, CSS an...
Jalal Mostafa
 
PPTX
Getting Started with Angular JS
Akshay Mathur
 
PPTX
Angular JS
John Temoty Roca
 
PPTX
Angular Js Basics
أحمد عبد الوهاب
 
PPTX
Angular js 1.0-fundamentals
Venkatesh Narayanan
 
PPTX
Angular Js Advantages - Complete Reference
EPAM Systems
 
PDF
Introduction to Sightly
Ankit Gubrani
 
PPTX
Bootstrap 4 ppt
EPAM Systems
 
Single Page Applications Workshop Part I: Interesting Topics in HTML5, CSS an...
Jalal Mostafa
 
Getting Started with Angular JS
Akshay Mathur
 
Angular JS
John Temoty Roca
 
Angular Js Basics
أحمد عبد الوهاب
 
Angular js 1.0-fundamentals
Venkatesh Narayanan
 
Angular Js Advantages - Complete Reference
EPAM Systems
 
Introduction to Sightly
Ankit Gubrani
 
Bootstrap 4 ppt
EPAM Systems
 

What's hot (20)

PPTX
Angular IO
Jennifer Estrada
 
PDF
jQuery
Ivano Malavolta
 
PPTX
Getting Started with jQuery
Akshay Mathur
 
PDF
Wt unit 5 client &amp; server side framework
PUNE VIDYARTHI GRIHA'S COLLEGE OF ENGINEERING, NASHIK
 
PDF
[2015/2016] Local data storage for web-based mobile apps
Ivano Malavolta
 
PPT
Jasig Rubyon Rails
Paul Pajo
 
PPTX
Angular js for Beginnners
Santosh Kumar Kar
 
KEY
An Introduction to Ruby on Rails
Joe Fiorini
 
PDF
Backbone.js
Ivano Malavolta
 
PPTX
AngularJS Introduction
Brajesh Yadav
 
DOCX
Controller in AngularJS
Brajesh Yadav
 
PDF
Introduction to AngularJS By Bharat Makwana
Bharat Makwana
 
PPTX
Building AngularJS Custom Directives
Dan Wahlin
 
PDF
Rest
Ivano Malavolta
 
PDF
jQuery - Chapter 3 - Effects
WebStackAcademy
 
PDF
Handlebars & Require JS
Ivano Malavolta
 
PDF
Ruby On Rails
Balint Erdi
 
PDF
JavaScript
Ivano Malavolta
 
DOCX
Shaping up with angular JS
Brajesh Yadav
 
KEY
Templates
soon
 
Angular IO
Jennifer Estrada
 
Getting Started with jQuery
Akshay Mathur
 
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
Ivano Malavolta
 
Jasig Rubyon Rails
Paul Pajo
 
Angular js for Beginnners
Santosh Kumar Kar
 
An Introduction to Ruby on Rails
Joe Fiorini
 
Backbone.js
Ivano Malavolta
 
AngularJS Introduction
Brajesh Yadav
 
Controller in AngularJS
Brajesh Yadav
 
Introduction to AngularJS By Bharat Makwana
Bharat Makwana
 
Building AngularJS Custom Directives
Dan Wahlin
 
jQuery - Chapter 3 - Effects
WebStackAcademy
 
Handlebars & Require JS
Ivano Malavolta
 
Ruby On Rails
Balint Erdi
 
JavaScript
Ivano Malavolta
 
Shaping up with angular JS
Brajesh Yadav
 
Templates
soon
 
Ad

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

PPTX
Basics of AngularJS
Filip Janevski
 
PPTX
Angular workshop - Full Development Guide
Nitin Giri
 
PPTX
Intro to AngularJs
SolTech, Inc.
 
PDF
One Weekend With AngularJS
Yashobanta Bai
 
PDF
AngularJS: Overview & Key Features
Mohamad Al Asmar
 
PPSX
Angular js
Arun Somu Panneerselvam
 
PDF
AngularJS Workshop
Gianluca Cacace
 
PDF
Everything You Need To Know About AngularJS
Sina Mirhejazi
 
PPT
Angular js
yogi_solanki
 
PPTX
Angular Presentation
Adam Moore
 
PPTX
Angularjs
Sabin Tamrakar
 
PDF
AngularJS Basics
Ravi Mone
 
PPTX
Learning AngularJS - Complete coverage of AngularJS features and concepts
Suresh Patidar
 
PPT
Angular js
Hritesh Saha
 
PPTX
Intoduction to Angularjs
Gaurav Agrawal
 
PPTX
Introduction to AngularJs
murtazahaveliwala
 
PPTX
Understanding angular js
Aayush Shrestha
 
PPTX
Practical AngularJS
Wei Ru
 
PPT
introduction to Angularjs basics
Ravindra K
 
Basics of AngularJS
Filip Janevski
 
Angular workshop - Full Development Guide
Nitin Giri
 
Intro to AngularJs
SolTech, Inc.
 
One Weekend With AngularJS
Yashobanta Bai
 
AngularJS: Overview & Key Features
Mohamad Al Asmar
 
AngularJS Workshop
Gianluca Cacace
 
Everything You Need To Know About AngularJS
Sina Mirhejazi
 
Angular js
yogi_solanki
 
Angular Presentation
Adam Moore
 
Angularjs
Sabin Tamrakar
 
AngularJS Basics
Ravi Mone
 
Learning AngularJS - Complete coverage of AngularJS features and concepts
Suresh Patidar
 
Angular js
Hritesh Saha
 
Intoduction to Angularjs
Gaurav Agrawal
 
Introduction to AngularJs
murtazahaveliwala
 
Understanding angular js
Aayush Shrestha
 
Practical AngularJS
Wei Ru
 
introduction to Angularjs basics
Ravindra K
 
Ad

Recently uploaded (20)

PDF
The Role of Automation and AI in EHS Management for Data Centers.pdf
TECH EHS Solution
 
PPTX
Can You Build Dashboards Using Open Source Visualization Tool.pptx
Varsha Nayak
 
PDF
Appium Automation Testing Tutorial PDF: Learn Mobile Testing in 7 Days
jamescantor38
 
PDF
Bandai Playdia The Book - David Glotz
BluePanther6
 
PDF
Build Multi-agent using Agent Development Kit
FadyIbrahim23
 
PDF
advancepresentationskillshdhdhhdhdhdhhfhf
jasmenrojas249
 
PDF
Jenkins: An open-source automation server powering CI/CD Automation
SaikatBasu37
 
PDF
Become an Agentblazer Champion Challenge
Dele Amefo
 
PDF
Protecting the Digital World Cyber Securit
dnthakkar16
 
PDF
What to consider before purchasing Microsoft 365 Business Premium_PDF.pdf
Q-Advise
 
PPTX
ASSIGNMENT_1[1][1][1][1][1] (1) variables.pptx
kr2589474
 
PPTX
ConcordeApp: Engineering Global Impact & Unlocking Billions in Event ROI with AI
chastechaste14
 
PDF
QAware_Mario-Leander_Reimer_Architecting and Building a K8s-based AI Platform...
QAware GmbH
 
PPTX
The-Dawn-of-AI-Reshaping-Our-World.pptxx
parthbhanushali307
 
PDF
Become an Agentblazer Champion Challenge Kickoff
Dele Amefo
 
PDF
Why Use Open Source Reporting Tools for Business Intelligence.pdf
Varsha Nayak
 
PDF
Microsoft Teams Essentials; The pricing and the versions_PDF.pdf
Q-Advise
 
PPTX
classification of computer and basic part of digital computer
ravisinghrajpurohit3
 
PPT
Activate_Methodology_Summary presentatio
annapureddyn
 
PPTX
Visualising Data with Scatterplots in IBM SPSS Statistics.pptx
Version 1 Analytics
 
The Role of Automation and AI in EHS Management for Data Centers.pdf
TECH EHS Solution
 
Can You Build Dashboards Using Open Source Visualization Tool.pptx
Varsha Nayak
 
Appium Automation Testing Tutorial PDF: Learn Mobile Testing in 7 Days
jamescantor38
 
Bandai Playdia The Book - David Glotz
BluePanther6
 
Build Multi-agent using Agent Development Kit
FadyIbrahim23
 
advancepresentationskillshdhdhhdhdhdhhfhf
jasmenrojas249
 
Jenkins: An open-source automation server powering CI/CD Automation
SaikatBasu37
 
Become an Agentblazer Champion Challenge
Dele Amefo
 
Protecting the Digital World Cyber Securit
dnthakkar16
 
What to consider before purchasing Microsoft 365 Business Premium_PDF.pdf
Q-Advise
 
ASSIGNMENT_1[1][1][1][1][1] (1) variables.pptx
kr2589474
 
ConcordeApp: Engineering Global Impact & Unlocking Billions in Event ROI with AI
chastechaste14
 
QAware_Mario-Leander_Reimer_Architecting and Building a K8s-based AI Platform...
QAware GmbH
 
The-Dawn-of-AI-Reshaping-Our-World.pptxx
parthbhanushali307
 
Become an Agentblazer Champion Challenge Kickoff
Dele Amefo
 
Why Use Open Source Reporting Tools for Business Intelligence.pdf
Varsha Nayak
 
Microsoft Teams Essentials; The pricing and the versions_PDF.pdf
Q-Advise
 
classification of computer and basic part of digital computer
ravisinghrajpurohit3
 
Activate_Methodology_Summary presentatio
annapureddyn
 
Visualising Data with Scatterplots in IBM SPSS Statistics.pptx
Version 1 Analytics
 

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.