This document provides an overview of single page applications and AngularJS. It discusses how AngularJS adds attributes to HTML to manipulate webpages using a MVC pattern. It also covers data binding, controllers, scopes, events, filters, routing and organizing code into modules and files. Key points include:
- Single page apps load a single HTML page and dynamically update it as the user interacts without reloading.
- AngularJS uses directives like ng-app and ng-model to extend HTML and bind data to the view.
- It follows an MVC pattern where the model stores data, the view displays it, and the controller handles user input.
- Data binding synchronizes the model and view.
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>
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>
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
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