AngularJS is a javascript framework for creating dynamic web applications. This presentation covers anatomy of angular application and concept of directives which is at core of angular. Only Angular 1.x is covered and code examples along with many concepts may not be valid with Angular 2.
1. JAVASCRIPT FRAMEWORK FOR CREATING
DYNAMIC WEB APPLICATIONS
(covers v 1.x only)
AngularJS
Anatomy
&
Directives
For code examples
https://github.com/agrawalakhil/angularjs-anatomy-directives
2. Hello!
I am Akhil Agrawal
Doing Javascript development since 2010,
using Angular for last 2 years & Node for 1 year
Started BIZense in 2008 & Digikrit in 2015
3. Let’s see the agenda
Evolution
Let’s start with an overview of
evolution of web application
development over time in last 6
years from 2011 to 2016
Concepts
Angular combines lot of good
programming concepts together
to create an effective & powerful
web app development framework
Anatomy
Anatomy of an AngularJS
application – Understanding
structure of an Angular app with
basic & advanced examples
Demos
Get familiar with wide range of
demos on different aspects of
AngularJS as well as complete
apps & opensource projects
Directives
Extend HTML with directives for
your application specific
functionality, abstracted into a
reusable & clean interface
Testing & Debugging
How AngularJS helps in creating
testable application and what
tools are available for testing &
debugging your app
4. 1.
Evolution
Let’s start with an overview of evolution of web application
development over time in last 6 years from 2011 to 2016
5. Web Development Evolution
Early Web – Pages, Server side scripting to render HTML
Flash/Flex – Rich Interactive Single Page Application
AJAX – Interactive, Client Side Processing, DOM manipulation,
Server Communication.
jQuery – Simplifies DOM manipulation, event binding, common api
across browsers, plugins to extend functionality.
REST – Common server side programming that can be used to build
web, mobile application and also for API integrations
Today– Separate Data/Display/Processing (MVC), Simplify
application development (shorter & cleaner code), Responsive For
Different Devices, Server interaction with REST API
6. Web Development Evolution : 2011-2014
Web Development in 2011
Flex & Silverlight For Rich & Interactive
Applications
jQuery (similar libraries) become
ubiquitous
HTML5 & CSS3 picks up
Working with AJAX
XML for data
XSLT to map XML data to HTML
jQuery or similar library for
callbacks
Web Development in 2012
Responsive, Mobile First & Bootstrap
Adobe discontinues Flash development
for Mobile
Javascript MVC Frameworks gets wide
adoption
API driven server side development
HTML5 & CSS3 becomes popular
Working with AJAX
JSON for data
JS templates to map JSON to HTML
jQuery or similar library for call
backs
Web Development in 2013
Simplified Design – CSS3, Web Fonts,
Icon Fonts & SVG
Responsive becomes ubiquitous with
Bootstrap while flash is in its ending
days
CSS Frameworks like SASS, LESS etc.
Many of Javascript (some MVC)
frameworks become popular – Ember,
Backbone, Angular, Knockout etc
Web IDEs & JS on server side
Working with AJAX
JSON for data (mostly from REST
API)
HTML5 CORS for cross domain AJAX
JS MVC Frameworks for JSON to
HTML mapping & for callbacks too
Web Development in 2014
Yeoman – Managing web apps
Advanced JS tooling for build (Grunt,
Gulp) and package management
(Bower, npm)
JS Testing Frameworks
Working with AJAX
JSON for data(mostly from REST
API)
JS MVC Frameworks for JSON to
HTML mapping & for callbacks too
7. Web Development Evolution : 2015-2016
Web Development in 2015
React gains popularity
Angular, Ember, Meteor all embrace
React
CSS Preprocessors like LESS & SASS
More web mvc frameworks like Flux
Microservices architecture over
monolithic
Moving towards four tier architecture
with client, delivery, aggregation &
services tier based on microservices
Not jQuery – manual DOM
manipulations are out
ECMA6/ECMA2015
Backend as service becoming popular
Rapid rise of NodeJS continues
Offline, Hybrid (web & native) and
Progressive web applications
Rise of diverse mobile devices,
wearables
Single Page Application is back in
fashion gaining popularity
Working with Ajax
Less dependence on HTTP long
polling as HTML5 support increases
Web socket adoption increases
Web Development in 2016
Angular 2 (Currently Release Candidate)
Moving towards social, semantic &
intelligently connected web
More server side javascript frameworks
like Meteor inspired from NodeJS
More microservices based architectures
in production
Web 3.0 (Semantic web) may pickup
with RDF, SPARQL, OWL & SKOS
Web IDE like Brackets.io may get more
adoption from web developers
Collaborative code sharing &
experimenting using tools like jsfiddle,
codeshare, dabblet
Visualization, graph and infographic
javascript libraries like D3
Reactive UIs with Angular 2.0
Working with Ajax
Increasing number of concurrent
connections
SDK based approach to API
integrations and server interactions
Progressive web apps working on the
principle of RAIL (Response,
Animation, Idle, Load)
8. 2.
Concepts
Angular combines lot of good programming concepts together to
create an effective & powerful web app development framework
10. Model-View-Controller (MVC)
Popular software architectural pattern – model
represents knowledge, views represents visual
representation and controllers control the view-
model relationship
MVC variations differ on connectivity, cardinality
and directionality – MVVM(Model-View-
ViewModel) & MVP (Model-View-Presenter)
AngularJS was closer to MVC for several years
but now is closer to MVVM ($scope object could
be considered ViewModel being decorated by
Controller)
11. MVC – Web Application
Model
The data
Controller
Controls behavior & view interactions
Modifying / updating the models
View
The interface, visual representation
How the data is presented to the user
JavaScript
HTML
12. Library vs Framework
Library – Provides passive functionality
and needs to be invoked or used by the
application – examples can be jQuery,
Backbone, Knockout
Framework – Provides application
architecture, handles common
requirements and invokes application
code – examples can be EmberJS and
AngularJS
14. Abstractions
jQuery abstracts browser
functionality like DOM
manipulation, traversal, handling
DOM events.
AngularJS abstracts relationship
between data and its visual display
through directives
15. Data Binding
Enables views to remain declarative
with clean separation of controllers
which don’t directly modify the
views
Two Way – views updated when
model changes and model changes
when view is modified – no more
DOM event handling
17. Dependency Injection
Container oriented programming which helps in
loose coupling and separation of concerns
No more global objects but only scoped objects
which will get their dependencies injected
Service creation independent of the usage
Good for modular code, allows AngularJS to wire
dependencies in correct order
Supports substitution for testing & patching
18. Modularity & Reusability
In AngularJS, modularity means the
components (controllers, filters, directives)
will live in modules
Benefits of modularization
Encapsulation
Context
Testability
Reusability
Reusable components can be packaged and
managed using bower (package manager)
19. Service Orientation
Service oriented architecture & microservices
architecture provides lot of benefits in context
of AngularJS applications
Services can be
developed independently
tested independently
deployed independently
scaled independently
distributed independently
monitored independently
composed and reused
orchestrated to create complex services
20. Test Driven Development
Testability was a fundamental objective of
AngularJS - Miško Hevery (AngularJS creator)
previously created JsTestDriver
Test Driven Development Lifecycle – Test
First, Make It Run, Improve It Further
Test Driven Development Benefits
Clarity of expectations before coding starts
Enhances confidence when refactoring
Tests acts as documentation
21. Separation of Design (Theme & Skin)
CSS Frameworks like SASS/LESS
Directives provides ways to create
components which can be
themed/skinned independently
Separation of visual design from
interaction logic using Controllers
22. Security
Sanitizing html & sanitize module
JSON Vulnerability – Redefining Array Constructor
XSRF
Strict Contextual Escaping
SCE assists in writing code in a way that
a) is secure by default
b) makes auditing for security vulnerabilities such as XSS,
clickjacking, etc. a lot easier
c) from v1.2, sce is enabled by default
d) whitelisting or blacklisting urls for sce to configure trusted
context using module config and $sceDelegateProvider
23. 3.
Anatomy
Anatomy of an AngularJS application – Understanding structure
of an Angular app with basic & advanced examples
24. Background - AngularJS
Open source, developed in 2009 by Misko Hevery & Adam
Abrons, maintained by Google
Hosted on Github (https://github.com/angular/angular.js) &
available under MIT License
Active development and large community with more than 1000
contributors
Uses jqlite (subset of jQuery) for DOM manipulation, will use
jQuery if included
Browser Support – Chrome, Safari, Firefox, Opera, IE 8+,
Mobile Browsers
Angular 2 has lot of improvements (to be released this year)
27. Basics
Scopes
Created with each controller, are nested and prototypically inherits from parent
controller’s scope
AngularJS has one root scope while directives can create isolated scopes
MVC
Model (Data in scopes)
View (Layout of data in HTML)
Controller (Code for handling view interactions)
Data Binding – Digest cycle for automated synching of changes
between view & model
Templates
Declarative view specification
HTML augmented with directives, markup, layout, filter & form
Loaded as single web view or dynamically as partial view
29. Basics – Another Example
Repeating
with
ng-repeat
<ul>
<li ng-repeat="cust in customers | orderBy:'name'">
{{ cust.name | uppercase }}
</li>
</ul>
<input type="text" ng-model="nameText" />
<ul>
<li ng-repeat="cust in customers | filter:nameText | orderBy:'name'">
{{ cust.name }} - {{ cust.city }}
</li>
</ul>
<html ng-app>
...
<div class="container"
ng-init="names=['Anuj','Nikhil','Ajit','Seema']">
<h3>Looping with the ng-repeat Directive</h3>
<ul>
<li ng-repeat="name in names">{{ name }}</li>
</ul>
</div>
...
</html> Using Filters
30. Basics – Continued
Routing
Mapping from url to view
Bind controller & define url parameters
Deep Linking
Update browser address bar & uses HTML5 history api with fallback to hashbang
(#!) urls
Makes views linkable using urls (server needs to recognize the links though &
rewrite if needed)
$routeProvider.when('/Book/:bookId', {
template: '<h2>Book {{params.bookId}}</h2>' +
'<ul><li ng-repeat="chapter in bookChapters[params.bookId]">' +
'<a href="#/Book/{{params.bookId}}/Chapter/{{$index+1}}">{{ chapter }}</a>' +
'</li></ul>',
controller: "BookController"
});
$routeProvider.when('/Book/:bookId/Chapter/:chapterId', {
template: '<h2>{{ bookChapters[params.bookId][params.chapterId] }}</h2>',
controller: "BookController"
});
31. Advanced
Forms
Declarative form validation
Variables for validation, dirty status - $valid, $dirty
Directives
Enhance HTML with custom element or attribute
Most important abstraction in AngularJS
Filters
Format displayed data like with currency
Filter & Sort data arrays
Services
Provides data (abstraction to get data from server)
Exists across views and can depend on other services
20+ services provided by AngularJS like $http, $q
32. Advanced – Continued
Scopes
Created with each controller, are nested and prototypically inherits from parent
controller’s scope
AngularJS has one root scope while directives can create isolated scopes
MVC
Model (Data in scopes)
View (Layout of data in HTML)
Controller (Code for handling view interactions)
Data Binding – Digest cycle for automated synching of changes
between view & model
Templates
Declarative view specification
HTML augmented with directives, markup, layout, filter & form
Loaded as single web view or dynamically as partial view
33. Server Communication
$http service – abstracts different ways of
communication over http, is asynchronous and
returns promise
Promises
Result of action
Particularly async
action
Either resolved
or rejected
$http({method: 'GET', url: 'customers.json'}).success(function(data, status) {
// process the data here
$scope.customers = data;
}).error(function(data, status) {
// error handling
$scope.customers = [];
});
var deferred = $q.defer();
$timeout(function() {
$http.get('customers.json').success(function(data) {
// process the data here
deferred.resolve(data);
}).error(function (error){
// error handling
deferred.reject();
});
}, 2000);
deferred.promise.then(function(data){
$scope.customers = data;
});
34. Handling Complexity
Directives
Package reusable HTML
Compile then Link phases
Supports scope, binding, restrictions, transclution
Can enable to create custom DSL
Modules
Packaging of JS code
Can declare dependencies (will decide
instantiation order)
Provides separation of namespaces
35. Modules – The Containers
<html ng-app="moduleName">
Factory
Service
Provider
Value
Filter
View Controller
*FactoryDirectives
Routes
Module
Config
$scope
37. Modules – Example Continued
View Injection
Factories
<div ng-view></div>
OR
<ng-view></ng-view>
var demoApp = angular.module('demoApp', [])
.factory('simpleFactory', function () {
var factory = {};
var customers = [ ... ];
factory.getCustomers = function () {
return customers;
};
return factory;
})
.controller('SimpleController', function ($scope, simpleFactory) {
$scope.customers = simpleFactory.getCustomers();
});
38. 4.
Demos
Get familiar with wide range of demos on different aspects of
AngularJS as well as complete apps & opensource projects
39. Demos
Data Binding
Watch
Templates
Controllers & Scopes
Repeat
Show/Hide
Data Binding – src, href, classes
Expressions
Events
Filters
Directives
Routing
Server Communication
Validation
Services
Promises
Dependencies & Modules
Scope Communication
40. More Demos
Wrapping jQuery Date Picker
Teams List App
File Upload
Simple Pagination Service
Cookies
I18n & l10n
Project Organization
Directives
Transclusion
Templating
ng-repeat
ng-switch
Content-Grid
Animation
Tourapt demo application
Kibana – In Opensource
41. 5.
Directives
Extend HTML with directives for your application specific
functionality, abstracted into a reusable & clean interface
42. Need
Reducing DOM
traversal for better
performance
Separation of DOM
manipulation logic from
business logic
Declarative approach
by extending HTML
elements to improve
readability & reusability
Directives are data
driven & conversational
$(document).ready(function() {
$('#someElement').somePlugin({opts});
});
<html>
<body>
<div some-directive></div>
</body>
</html>
43. Deconstruction
Definition
return link function
specify link function and return
definition object
Naming – ngApp beomes ng-app,
ng:app, ng_app, x-ng-app, data-ng-app
Attachment Styles – element, attribute,
class or comment
Configuration
priority – order of execution
terminal – execution should stop after
this priority
replace – whether to replace or
transclude
Templating
template
templateUrl
Compiling & Linking
compile – does the compilation of
directive and returns the linker
linking – using data from scope for
making the directive functional
Controller & require
needs controller access of another
directive
require
ngModel - look for ngModel directive
on same element
?ngModel - make ngModel optional
^ngModel - look upwards (parent
elements) for ngModel
Transclusion
is translated inclusion
use ng-transclude when content is
unaltered
use controller & $transclude when
content is altered
44. Execution
Seq Function DOM Transclude $scope Callable by Child
1 compile
DOM has not been compiled but template has
been loaded into the DOM element content
area. Directives can be added and removed.
DOM can be manipulated with both DOM
functions and HTML string replacement.
Transclude
function is
available but is
deprecated
and should not
be called.
Not available.
Function cannot
be called by child
elements.
2 controller
Compiled DOM element is available but
should not be modified. Transcluded child
content has not been added to the DOM
element. No DOM changes should occur
because this is a controller and transcluded
child content has not been linked in yet.
Transclude
function is
available but
should not be
called.
$scope is available
and can be used.
Function
parameters are
injected using
the $injector service
.
Function is passed
into child directive
linking functions
and is callable by
them.
3 pre-link
Compiled DOM element is available but
should not be modified because child directive
DOM elements have not been linked in yet.
Transclude
function is
available but
should not be
called.
$scope is available
and can be modified.
Function is not
callable by child
directives. But
may call the
controllers of
parent directives.
4 post-link
Compiled DOM element and child directive
DOM elements are available. DOM can be
modified with DOM functions only (no HTML
replacement) and only content that does not
require compilation can be added.
Transclude
function is
available and
may be called.
$scope is available
and may be used.
Not callable by
directive children
but may call the
controller of
parent directives.
Reference: https://www.toptal.com/angular-js/angular-js-demystifying-directives
45. Complete Example – Stop Watch
Requirements
Track time
Start/Stop
Reset to Zero
Log each lap
<div stop-watch
options="stopWatchOptions">
<h2>{{stopWatchOptions.elapsedTime
| date:'MM/dd/yyyy @ h:mma #
s:sss'}}</h2>
<button ng-
click="startTimer()">Start</button>
<button ng-
click="stopTimer()">Stop</button>
<button ng-
click="resetTimer()">Reset</button>
</div>
compile: function(tElem, tAttrs){
if (!tAttrs.options) throw new Error('Options missing for stopwatch directive');
return function(scope, elem, attrs, controller, transclude) {
var stopWatchService = new StopWatchFactory(scope[attrs.options]);
scope.startTimer = stopWatchService.startTimer;
scope.stopTimer = stopWatchService.stopTimer;
scope.resetTimer = stopWatchService.resetTimer;
};
}
stopWatchApp.factory('StopWatchFactory',
['$interval', function($interval){
return function(options){
var startTime = 0,
currentTime = null,
offset = 0,
interval = null,
self = this;
…
self.startTimer = function(){
if(self.running === false){
startTime = new
Date().getTime();
interval =
$interval(self.updateTime,options.interval);
self.running = true;
}
};
};
}]);
47. 6.
Testing & Debugging
How AngularJS helps in creating testable application and what
tools are available for testing & debugging your app
48. Tooling
Testing Libraries
Assertion libraries like chai
Mock Libraries like angular-mocks, mocha
Testing Frameworks
Behavior driven testing framework like Jasmine
Test runners like Karma
End-to-end testing frameworks like Protractor
Debugging Tools
Inspecting DOM
Debugger statement
Angular Batarang – Chrome extension
49. Testing – Unit Tests
Installing Karma & Jasmine
Use npm to install karma,
jasmine etc
Karma command line to run
directly or configure npm
test script
Jasmine
behavior driven testing
included matchers toBe
and toEqual, toMatch,
toBeDefined,
toBeUndefined, toBeNull,
toContain, toBeLessThan,
toBeGreaterThan, toThrow
custom matchers
npm install karma --save-dev
npm install -g karma-cli
npm install karma-jasmine –save-dev
npm install karma-chrome-launcher --save-dev
karma init karma.conf.js
karma start karma.conf.js
describe('customers', function () {
it('customers array length is 2',
function () {
var $scope = {};
var controller =
$controller('SimpleController',
{ $scope: $scope });
expect($scope.customers.length)
.toBe(2);
});
});
50. Debugging
Debugging from DOM using angular.element
var rootEle = document.querySelector("html");
var ele = angular.element(rootEle);
Debugger statement
getCurrentUser: function() {
debugger;// Set debugger inside this function
return service.user_id;
}
Angular Batarang – Chrome extension that acts as
a debugging tool for Angular apps
51. Libraries
AngularJS UI (https://github.com/angular-ui)
calendar, date, map etc.
UI Bootstrap
ng-grid – data grid
ui-router – enhanced routing with ui states
ui-utils – lot of utilities for developing with AngularJS
Lazy Loading
OC Lazy Load (https://github.com/ocombe/ocLazyLoad)
RequireJS (http://requirejs.org/)
AngularStrap (http://mgcrea.github.io/angular-strap/)
Native directives for integrating Bootstrap 3
Many Other Useful Libraries
Utilities like ui-router-extras, angular-touch, angular-translate, angular-
toaster, editors like textAngular or video player like videogular etc.
54. Angular2 vs Angular1 – Key Differences
Angular2 is entirely component based, controllers
and $scope are no longer used and are replaced by
directives & components. Components are just
directives with a template
Directives are considerably simplified
Improved dependency injection model in Angular2
TypeScript in Angular2
TypeScript = ES6 + Types + Annotations
Generics & Lambdas with TypeScript
Reference: https://dzone.com/articles/typed-front-end-with-angular-2
55. Thanks!
Any questions?
You can find me at:
@digikrit
akhil@digikrit.com
Special thanks to all the people who made and released these awesome
resources for free:
Presentation template by SlidesCarnival
Presentation models by SlideModel
JS, AngularJS, NodeJS community & companies behind these projects