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...
PPTX
Getting Started with Angular JS
PPTX
Angular JS
PPTX
Angular Js Basics
PPTX
Angular js 1.0-fundamentals
PPTX
Angular Js Advantages - Complete Reference
PDF
Introduction to Sightly
PPTX
Bootstrap 4 ppt
Single Page Applications Workshop Part I: Interesting Topics in HTML5, CSS an...
Getting Started with Angular JS
Angular JS
Angular Js Basics
Angular js 1.0-fundamentals
Angular Js Advantages - Complete Reference
Introduction to Sightly
Bootstrap 4 ppt

What's hot (20)

PPTX
Angular IO
PDF
PPTX
Getting Started with jQuery
PDF
Wt unit 5 client &amp; server side framework
PDF
[2015/2016] Local data storage for web-based mobile apps
PPT
Jasig Rubyon Rails
PPTX
Angular js for Beginnners
KEY
An Introduction to Ruby on Rails
PDF
Backbone.js
PPTX
AngularJS Introduction
DOCX
Controller in AngularJS
PDF
Introduction to AngularJS By Bharat Makwana
PPTX
Building AngularJS Custom Directives
PDF
PDF
jQuery - Chapter 3 - Effects
PDF
Handlebars & Require JS
PDF
Ruby On Rails
PDF
JavaScript
DOCX
Shaping up with angular JS
KEY
Templates
Angular IO
Getting Started with jQuery
Wt unit 5 client &amp; server side framework
[2015/2016] Local data storage for web-based mobile apps
Jasig Rubyon Rails
Angular js for Beginnners
An Introduction to Ruby on Rails
Backbone.js
AngularJS Introduction
Controller in AngularJS
Introduction to AngularJS By Bharat Makwana
Building AngularJS Custom Directives
jQuery - Chapter 3 - Effects
Handlebars & Require JS
Ruby On Rails
JavaScript
Shaping up with angular JS
Templates
Ad

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

PPTX
Basics of AngularJS
PPTX
Angular workshop - Full Development Guide
PPTX
Intro to AngularJs
PDF
One Weekend With AngularJS
PDF
AngularJS: Overview & Key Features
PPSX
PDF
AngularJS Workshop
PDF
Everything You Need To Know About AngularJS
PPT
Angular js
PPTX
Angular Presentation
PPTX
Angularjs
PDF
AngularJS Basics
PPTX
Learning AngularJS - Complete coverage of AngularJS features and concepts
PPT
Angular js
PPTX
Intoduction to Angularjs
PPTX
Introduction to AngularJs
PPTX
Understanding angular js
PPTX
Practical AngularJS
PPT
introduction to Angularjs basics
Basics of AngularJS
Angular workshop - Full Development Guide
Intro to AngularJs
One Weekend With AngularJS
AngularJS: Overview & Key Features
AngularJS Workshop
Everything You Need To Know About AngularJS
Angular js
Angular Presentation
Angularjs
AngularJS Basics
Learning AngularJS - Complete coverage of AngularJS features and concepts
Angular js
Intoduction to Angularjs
Introduction to AngularJs
Understanding angular js
Practical AngularJS
introduction to Angularjs basics
Ad

Recently uploaded (20)

PDF
Raksha Bandhan Grocery Pricing Trends in India 2025.pdf
PPTX
Introduction to Artificial Intelligence
PDF
top salesforce developer skills in 2025.pdf
PDF
Flood Susceptibility Mapping Using Image-Based 2D-CNN Deep Learnin. Overview ...
PPTX
history of c programming in notes for students .pptx
PDF
Upgrade and Innovation Strategies for SAP ERP Customers
PDF
Addressing The Cult of Project Management Tools-Why Disconnected Work is Hold...
PDF
How to Choose the Right IT Partner for Your Business in Malaysia
PDF
Claude Code: Everyone is a 10x Developer - A Comprehensive AI-Powered CLI Tool
PDF
System and Network Administration Chapter 2
PDF
How Creative Agencies Leverage Project Management Software.pdf
PDF
PTS Company Brochure 2025 (1).pdf.......
PDF
AI in Product Development-omnex systems
PPTX
ISO 45001 Occupational Health and Safety Management System
PDF
Internet Downloader Manager (IDM) Crack 6.42 Build 42 Updates Latest 2025
PDF
Internet Downloader Manager (IDM) Crack 6.42 Build 41
PDF
How to Migrate SBCGlobal Email to Yahoo Easily
PDF
Wondershare Filmora 15 Crack With Activation Key [2025
PPTX
CHAPTER 2 - PM Management and IT Context
PDF
Understanding Forklifts - TECH EHS Solution
Raksha Bandhan Grocery Pricing Trends in India 2025.pdf
Introduction to Artificial Intelligence
top salesforce developer skills in 2025.pdf
Flood Susceptibility Mapping Using Image-Based 2D-CNN Deep Learnin. Overview ...
history of c programming in notes for students .pptx
Upgrade and Innovation Strategies for SAP ERP Customers
Addressing The Cult of Project Management Tools-Why Disconnected Work is Hold...
How to Choose the Right IT Partner for Your Business in Malaysia
Claude Code: Everyone is a 10x Developer - A Comprehensive AI-Powered CLI Tool
System and Network Administration Chapter 2
How Creative Agencies Leverage Project Management Software.pdf
PTS Company Brochure 2025 (1).pdf.......
AI in Product Development-omnex systems
ISO 45001 Occupational Health and Safety Management System
Internet Downloader Manager (IDM) Crack 6.42 Build 42 Updates Latest 2025
Internet Downloader Manager (IDM) Crack 6.42 Build 41
How to Migrate SBCGlobal Email to Yahoo Easily
Wondershare Filmora 15 Crack With Activation Key [2025
CHAPTER 2 - PM Management and IT Context
Understanding Forklifts - TECH EHS Solution

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.