KEMBAR78
Basics of AngularJS | PPTX
BASICS OF ANGULARJS
TOPICS
 Definition
 Key features
 Demo examples
 Exercises
DEFINITION
• Web application framework
• Default MVC framework… but not required
• JavaScript library
• Open source
• Maintained by Google
• Used for single page application (SPA)
• Provide templating mechanism
• Has the largest user base
• Easy to test
• . . .
KEY FEATURES
2-WAY DATA
BINDING
DEPENCENCY
INJECTION
TEMPLATING
EXPRESSIONS
MVC DIRECTIVES
FILTERS SERVICES
TESTING
MODULARITY
SCOPING
ANIMATIONS
FACTORIES PROVIDERS
ROUTING VALIDATION
CONTROLLERS
CONSTANTS
KEY FEATURES
2-WAY DATA
BINDING
DEPENCENCY
INJECTION
TEMPLATING
EXPRESSIONS
MVC DIRECTIVES
FILTERS SERVICES
TESTING
MODULARITY
SCOPING
ANIMATIONS
FACTORIES PROVIDERS
ROUTING VALIDATION
CONTROLLERS
CONSTANTS
MVC
Stores data retrieved from the controller logic and shown on the viewmodel
controller
view Display the model data to the user
Manipulate with the model data or the associate representation of the
data on the view
View
Model
Controller
Update
UI
Update
model
Model
changed
User
action
Model
change
d
2-WAY DATA BINDING
|
E-mail address:
var email = áżžáżž;
watche
r
watche
r
Binds the value of the model to the view and does not have
additional way to determine if the value in the view has been
changed by the user
1-way
2-way Binds the value of the model to the view while also bind the input on
the view with the model, so when the input is changed the value of
the model is changed as well
DEPENDENCY INJECTION (DI)
• Increase modularity
• Makes the program extensible
• Separation of concerns
• Single responsibility
• Components easy to test and maintain
Dependency Injection is a software design pattern in which components are given
their dependencies instead of hard coding them within the component.
definition
usage
TECHNOLOGY STACK
HOW TO START?
• Angular is designed for SPA. We are going to have one main HTML file that
includes all info that is necessary so that Angular can function normally.
• Angular is nothing more but an JavaScript library. Download it and include it in
your HTML!
LINK:
https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js
• Download it as NPM dependency:
npm install --save angular
HOW TO START?
• The Angular application starts from the DOM element where the ng-
app is declared
• ng-app holds the name of the Angular application
<div ng-app="myApp"></div>
• Declare the name of the application in separate JS file and include it in the main HTML
file
const app = angular.module('myApp', []);
CONTROLLER
• Controls the data flow
• Create controller on given module:
app.controller('myCtrl', () => {
. . .
});
• Tell the application where you want this controller to be in action on the HTML:
<div ng-controller="myCtrl"></div>
• Make sure that the ng-controller is nested inside the DOM element where ng-app
attribute is attached!
• The controller is a constructor function which is initialized when Angular
discovers the ng-controller directive.
$SCOPE
• For the controller instance a child scope object is created and injected as a
dependency of the constructor function.
• Every function and model that is defined in the controller and applied on the view
must be augmented to the $scope object.
app.controller('myCtrl', ($scope) => {
$scope.company = 'Endava';
}); Dependen
cy
Injection
$ROOTSCOPE
• For each Angular application there is only one root scope: $rootScope which
contains all children scopes.
• Child scope - $scope is the scope of the controller.
• On controller scope can be a parent of another scope if the second controller
is nested in the first one.
• Scoping forms tree hierarchy in the application
• Every time a expression is added in the HTML it is the $scope of the controller
which is searched first. If the expression is not found, the parent scope is
searched.
$ROOTSCOPE
<body ng-app='app‘>
{{someValue}}
<div ng-controller='ctrl1'>
</div>
<div ng-controller='ctrl2'>
</div>
<div ng-controller='ctrl3'>
{{someValue}}
</div>
</body>
$rootScope
$scope
$scope
$scope
someValue
EXPRESSIONS
• Data binding on HTML is done with expressions
• They are much like JavaScript expressions (except they forbid function declaration
as expression)
• They are evaluated against the $scope object
• Style of writing expressions:
• Using ng-bind: <span ng-bind='email'></span>
• Using double curly notation: <span> {{email}} </span>
Examples:
• <span>{{ 2 + 5 }}</span>
• <p>{{ user.email }}</p>
• <button ng-click='saveUser()'>SAVE</button>
EXPRESSIONS
app.controller('myCtrl', ($scope) => {
$scope.company = 'Endava';
});
<div ng-app=‘myApp‘>
<div ng-controller=‘myCtrl‘>
Company name: {{ company }}
</div>
</div>
JavaScript
HTML
SERVICE
• Function or object used to organize and share code across the application
• The service is wired to the controller using DI
• Every service is wrapped to an provider and like that is available everywhere in the
application
• It is lazy instantiated – only when it is needed
• It is singleton – is instantiated only once
• They are invoked as a constructor with the new keyword
app.service('myService', class {
getName() { . . . }
getEmail() { . . . }
});
FACTORY
• Similar to services
• They are invoked as functions, not as constructor functions
• Can be wired to the controller using DI
• The controller will have the value returned from the invocation of the function
instance which is the second argument of factory() method.
app.factory('myService', () =>({
getName: function() { . . . },
getEmail: function() { . . . }
}));
FACTORY
app.factory('myService', () => ({
getName: function() { return 'Endava' }
}));
app.controller(‘myCtrl‘, ($scope, myService) => {
$scope.company = myService.getName();
});
BUILD-IN SERVICES
• There are 30 build-in services in Angular
• $http used for HTTP request
• $location makes the URL available in the application
• $window window object wrapper
• $animate used for animations
• $filter contains default filters
• $httpBackend used for HTTP requests in testing
• $locale used for localization
• $parse used for parsing content
• $q used for resolving/rejecting promises
• $timeout timeout wrapper
• . . . etc
$HTTP
• $http is a build-in service for asynchronous HTTP requests
• All HTTP methods of $http return promise object which:
• resolved successfully – code 200
• rejected – code 4XX, 5XX
• General usage:
$http({
method:'post',
url:'/api/users',
data: userObject
}).then((response) => {
// success
}, (error) => {
// error
});
$http({
method:'get',
url:'/api/user‘,
params: {
userId: 1
}
}).then((response) => {
// success
}, (error) => {
// error
});
DIRECTIVE
• Angular allows us to extend HTML with new attributes called directives
• Build-in directives:
• ng-app initialize Angular application
• ng-controller initialize controller
• ng-init create init values that are used in the controller
• ng-bind bind expression on HTML (1-way data binding)
• ng-model allow 2-way data binding. Used on input elements
• ng-repeat used for iterations
• ng-options used for iterative population of options in select element
• ng-if will show the element to which it is attached if the
condition is satisfied
• ng-disabled if true disables the DOM element
• ng-selected if true for checkbox, the checkbox will be checked
• ng-readonly makes a text field read only
• ng-href allow Angular variable to be binded to the href attribute
• . . . etc
DIRECTIVE
Examples:
$scope.cities = [
{name: 'Skopje', country: 'MKD'},
{name: 'Washington', country: 'US'},
{name: 'Moscow', country: 'RU'},
];
<tr ng-repeat=“city in cities track by $index”>
<td>{{city.name}}</td>
<td>{{city.country}}</td>
</tr>
<option ng-options=“city.name for city in cities track by $index”></option>
CUSTOM DIRECTIVE
• Custom directive can be:
• Element <endava-title></end-user-list>
• Attribute <div endava-user-list></div>
• Class name <div class='endava-user-list'></div>
• Comment <!-- directive: endava-user-list -->
• Directive are always declared with camel-case but used with kebab-case
Example:
app.directive('endavaTitle', () => ({
restrict: 'E',
template: ''<h1>E N D A V A</h1>''
})); <endava-title></endava-title>
Used as:
CUSTOM DIRECTIVE
• Restriction:
• Element E
• Attribute A
• Comment M
• Class C
• By default the restrict value is EA which means that the directive can be used as
element or attribute
• template vs. templateUrl property app.directive('endavaTitle', () => ({
restrict: 'E',
templateUrl: ‘/pages/index.html'
}));
CUSTOM DIRECTIVE
• Scope of directive
• Can use the scope of the controller
• Can have isolated scope:
app.directive('endavaTitle', function() {
return {
restrict: 'A',
templateUrl: '/pages/title.html',
scope: {
title: ‘@companyName'
}
}
});
<h1>{{title}}</h1>
<div>
<endava-title company-name='ENDAVA‘>
</endava-title>
</div>
/pages/title.html
/index.html
@ string binding
= 2-way data
binding
& method
reference
DIGEST CYCLE, DIRTY CHECKING
AND WATCHERS
Model
Dirty
checkin
g
watcher
watcher
watcher
{{E}}
ng-model
ng-bind
Dirty checking
VIEW
EVENT
TIME FOR
PRACTICE
EXERCISES
1.Create an Angular application that will display
the top 20 movies that are now playing in
theaters around the world!
2.Extend the previous application with an option
to see list of actors and actresses for each
movie!
3.Extend the list of movies so that the user can
load more movies from the same list of movies
EXERCISES
Use the APIs provided by themoviedb.org
API endpoints:
• Movies that are now playing:
https://api.themoviedb.org/3/movie/now_playing?api_key={api_key}
https://api.themoviedb.org/3/movie/now_playing?api_key={api_key}&page={page_number}
•List of actors and actresses for a given movie:
https://api.themoviedb.org/3/movie/{movie_id}/credits?api_key={api_key}
• Images endpoint:
https://image.tmdb.org/t/p/w185/{img_path}
api_key=6e44c855f8bb700398820bc37a01ff6c
For more info: https://developers.themoviedb.org/3/getting-started
EXTRA EXERCISES
4.Create directive for rating movies!
5.Extend the application so that the user should
be able to filter movies by genre type. The API
endpoint for genres:
https://api.themoviedb.org/3/genre/movie/list?api_key={api_ke
y}
QUESTIONS
THANK YOU!
Filip Janevski
Skype: en_fjanevski
Mail: filip.janevski@endava.com
Presentation
http://www.slideshare.net/FilipJanevski1/basics-of-angularjs

Basics of AngularJS

  • 1.
  • 2.
    TOPICS  Definition  Keyfeatures  Demo examples  Exercises
  • 3.
    DEFINITION • Web applicationframework • Default MVC framework… but not required • JavaScript library • Open source • Maintained by Google • Used for single page application (SPA) • Provide templating mechanism • Has the largest user base • Easy to test • . . .
  • 4.
    KEY FEATURES 2-WAY DATA BINDING DEPENCENCY INJECTION TEMPLATING EXPRESSIONS MVCDIRECTIVES FILTERS SERVICES TESTING MODULARITY SCOPING ANIMATIONS FACTORIES PROVIDERS ROUTING VALIDATION CONTROLLERS CONSTANTS
  • 5.
    KEY FEATURES 2-WAY DATA BINDING DEPENCENCY INJECTION TEMPLATING EXPRESSIONS MVCDIRECTIVES FILTERS SERVICES TESTING MODULARITY SCOPING ANIMATIONS FACTORIES PROVIDERS ROUTING VALIDATION CONTROLLERS CONSTANTS
  • 6.
    MVC Stores data retrievedfrom the controller logic and shown on the viewmodel controller view Display the model data to the user Manipulate with the model data or the associate representation of the data on the view View Model Controller Update UI Update model Model changed User action Model change d
  • 7.
    2-WAY DATA BINDING | E-mailaddress: var email = áżžáżž; watche r watche r Binds the value of the model to the view and does not have additional way to determine if the value in the view has been changed by the user 1-way 2-way Binds the value of the model to the view while also bind the input on the view with the model, so when the input is changed the value of the model is changed as well
  • 8.
    DEPENDENCY INJECTION (DI) •Increase modularity • Makes the program extensible • Separation of concerns • Single responsibility • Components easy to test and maintain Dependency Injection is a software design pattern in which components are given their dependencies instead of hard coding them within the component. definition usage
  • 9.
  • 10.
    HOW TO START? •Angular is designed for SPA. We are going to have one main HTML file that includes all info that is necessary so that Angular can function normally. • Angular is nothing more but an JavaScript library. Download it and include it in your HTML! LINK: https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js • Download it as NPM dependency: npm install --save angular
  • 11.
    HOW TO START? •The Angular application starts from the DOM element where the ng- app is declared • ng-app holds the name of the Angular application <div ng-app="myApp"></div> • Declare the name of the application in separate JS file and include it in the main HTML file const app = angular.module('myApp', []);
  • 12.
    CONTROLLER • Controls thedata flow • Create controller on given module: app.controller('myCtrl', () => { . . . }); • Tell the application where you want this controller to be in action on the HTML: <div ng-controller="myCtrl"></div> • Make sure that the ng-controller is nested inside the DOM element where ng-app attribute is attached! • The controller is a constructor function which is initialized when Angular discovers the ng-controller directive.
  • 13.
    $SCOPE • For thecontroller instance a child scope object is created and injected as a dependency of the constructor function. • Every function and model that is defined in the controller and applied on the view must be augmented to the $scope object. app.controller('myCtrl', ($scope) => { $scope.company = 'Endava'; }); Dependen cy Injection
  • 14.
    $ROOTSCOPE • For eachAngular application there is only one root scope: $rootScope which contains all children scopes. • Child scope - $scope is the scope of the controller. • On controller scope can be a parent of another scope if the second controller is nested in the first one. • Scoping forms tree hierarchy in the application • Every time a expression is added in the HTML it is the $scope of the controller which is searched first. If the expression is not found, the parent scope is searched.
  • 15.
    $ROOTSCOPE <body ng-app='app‘> {{someValue}} <div ng-controller='ctrl1'> </div> <divng-controller='ctrl2'> </div> <div ng-controller='ctrl3'> {{someValue}} </div> </body> $rootScope $scope $scope $scope someValue
  • 16.
    EXPRESSIONS • Data bindingon HTML is done with expressions • They are much like JavaScript expressions (except they forbid function declaration as expression) • They are evaluated against the $scope object • Style of writing expressions: • Using ng-bind: <span ng-bind='email'></span> • Using double curly notation: <span> {{email}} </span> Examples: • <span>{{ 2 + 5 }}</span> • <p>{{ user.email }}</p> • <button ng-click='saveUser()'>SAVE</button>
  • 17.
    EXPRESSIONS app.controller('myCtrl', ($scope) =>{ $scope.company = 'Endava'; }); <div ng-app=‘myApp‘> <div ng-controller=‘myCtrl‘> Company name: {{ company }} </div> </div> JavaScript HTML
  • 18.
    SERVICE • Function orobject used to organize and share code across the application • The service is wired to the controller using DI • Every service is wrapped to an provider and like that is available everywhere in the application • It is lazy instantiated – only when it is needed • It is singleton – is instantiated only once • They are invoked as a constructor with the new keyword app.service('myService', class { getName() { . . . } getEmail() { . . . } });
  • 19.
    FACTORY • Similar toservices • They are invoked as functions, not as constructor functions • Can be wired to the controller using DI • The controller will have the value returned from the invocation of the function instance which is the second argument of factory() method. app.factory('myService', () =>({ getName: function() { . . . }, getEmail: function() { . . . } }));
  • 20.
    FACTORY app.factory('myService', () =>({ getName: function() { return 'Endava' } })); app.controller(‘myCtrl‘, ($scope, myService) => { $scope.company = myService.getName(); });
  • 21.
    BUILD-IN SERVICES • Thereare 30 build-in services in Angular • $http used for HTTP request • $location makes the URL available in the application • $window window object wrapper • $animate used for animations • $filter contains default filters • $httpBackend used for HTTP requests in testing • $locale used for localization • $parse used for parsing content • $q used for resolving/rejecting promises • $timeout timeout wrapper • . . . etc
  • 22.
    $HTTP • $http isa build-in service for asynchronous HTTP requests • All HTTP methods of $http return promise object which: • resolved successfully – code 200 • rejected – code 4XX, 5XX • General usage: $http({ method:'post', url:'/api/users', data: userObject }).then((response) => { // success }, (error) => { // error }); $http({ method:'get', url:'/api/user‘, params: { userId: 1 } }).then((response) => { // success }, (error) => { // error });
  • 23.
    DIRECTIVE • Angular allowsus to extend HTML with new attributes called directives • Build-in directives: • ng-app initialize Angular application • ng-controller initialize controller • ng-init create init values that are used in the controller • ng-bind bind expression on HTML (1-way data binding) • ng-model allow 2-way data binding. Used on input elements • ng-repeat used for iterations • ng-options used for iterative population of options in select element • ng-if will show the element to which it is attached if the condition is satisfied • ng-disabled if true disables the DOM element • ng-selected if true for checkbox, the checkbox will be checked • ng-readonly makes a text field read only • ng-href allow Angular variable to be binded to the href attribute • . . . etc
  • 24.
    DIRECTIVE Examples: $scope.cities = [ {name:'Skopje', country: 'MKD'}, {name: 'Washington', country: 'US'}, {name: 'Moscow', country: 'RU'}, ]; <tr ng-repeat=“city in cities track by $index”> <td>{{city.name}}</td> <td>{{city.country}}</td> </tr> <option ng-options=“city.name for city in cities track by $index”></option>
  • 25.
    CUSTOM DIRECTIVE • Customdirective can be: • Element <endava-title></end-user-list> • Attribute <div endava-user-list></div> • Class name <div class='endava-user-list'></div> • Comment <!-- directive: endava-user-list --> • Directive are always declared with camel-case but used with kebab-case Example: app.directive('endavaTitle', () => ({ restrict: 'E', template: ''<h1>E N D A V A</h1>'' })); <endava-title></endava-title> Used as:
  • 26.
    CUSTOM DIRECTIVE • Restriction: •Element E • Attribute A • Comment M • Class C • By default the restrict value is EA which means that the directive can be used as element or attribute • template vs. templateUrl property app.directive('endavaTitle', () => ({ restrict: 'E', templateUrl: ‘/pages/index.html' }));
  • 27.
    CUSTOM DIRECTIVE • Scopeof directive • Can use the scope of the controller • Can have isolated scope: app.directive('endavaTitle', function() { return { restrict: 'A', templateUrl: '/pages/title.html', scope: { title: ‘@companyName' } } }); <h1>{{title}}</h1> <div> <endava-title company-name='ENDAVA‘> </endava-title> </div> /pages/title.html /index.html @ string binding = 2-way data binding & method reference
  • 28.
    DIGEST CYCLE, DIRTYCHECKING AND WATCHERS Model Dirty checkin g watcher watcher watcher {{E}} ng-model ng-bind Dirty checking VIEW EVENT
  • 29.
  • 30.
    EXERCISES 1.Create an Angularapplication that will display the top 20 movies that are now playing in theaters around the world! 2.Extend the previous application with an option to see list of actors and actresses for each movie! 3.Extend the list of movies so that the user can load more movies from the same list of movies
  • 31.
    EXERCISES Use the APIsprovided by themoviedb.org API endpoints: • Movies that are now playing: https://api.themoviedb.org/3/movie/now_playing?api_key={api_key} https://api.themoviedb.org/3/movie/now_playing?api_key={api_key}&page={page_number} •List of actors and actresses for a given movie: https://api.themoviedb.org/3/movie/{movie_id}/credits?api_key={api_key} • Images endpoint: https://image.tmdb.org/t/p/w185/{img_path} api_key=6e44c855f8bb700398820bc37a01ff6c For more info: https://developers.themoviedb.org/3/getting-started
  • 32.
    EXTRA EXERCISES 4.Create directivefor rating movies! 5.Extend the application so that the user should be able to filter movies by genre type. The API endpoint for genres: https://api.themoviedb.org/3/genre/movie/list?api_key={api_ke y}
  • 33.
  • 34.
    THANK YOU! Filip Janevski Skype:en_fjanevski Mail: filip.janevski@endava.com Presentation http://www.slideshare.net/FilipJanevski1/basics-of-angularjs