AngularJS Anatomy & Directives
-
Upload
digikrit -
Category
Technology
-
view
5.049 -
download
0
Transcript of AngularJS Anatomy & Directives
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
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
Let’s see the agenda
EvolutionLet’s start with an overview of evolution of web application development over time in last 6 years from 2011 to 2016
ConceptsAngular combines lot of good programming concepts together to create an effective & powerful web app development framework
AnatomyAnatomy of an AngularJS application – Understanding structure of an Angular app with basic & advanced examples
DemosGet familiar with wide range of demos on different aspects of AngularJS as well as complete apps & opensource projects
DirectivesExtend HTML with directives for your application specific functionality, abstracted into a reusable & clean interface
Testing & DebuggingHow AngularJS helps in creating testable application and what tools are available for testing & debugging your app
1.Evolution
Let’s start with an overview of evolution of web application development over time in last 6 years from 2011 to 2016
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 apiacross 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
Web Development Evolution : 2011-2014Web 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
Web Development Evolution : 2015-2016Web 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)
2.Concepts
Angular combines lot of good programming concepts together to create an effective & powerful web app development framework
Imperative vs Declarative
jQuery Imperative Wiring
Angular Declarative Relationship
<input type="text" id="yourName"><h1 id="helloName"></h1><script type="text/javascript”>$(function() {$("#yourName").keyup(function () {$("#helloName").text("Hello " + this.value + "!");
});});
</script>
<input type="text" ng-model="yourName"><h1>Hello {{yourName}}!</h1>
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)
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
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
Single Page Application
View1
View2
View3View4
View5
http://application.com/ #/view1
http://application.com/#/view2
http://application.com/#/view3
http://application.com/#/view4
http://application.com/#/view5
Abstractions
jQuery abstracts browser functionality like DOM manipulation, traversal, handling DOM events.
AngularJS abstracts relationship between data and its visual display through directives
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
Data Binding Illustration
Scope is basically acting as the ViewModel which enables two way data binding
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
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)
Service Orientation
Service oriented architecture & microservicesarchitecture provides lot of benefits in context of AngularJS applications
Services can bedeveloped independentlytested independentlydeployed independentlyscaled independentlydistributed independentlymonitored independentlycomposed and reusedorchestrated to create complex services
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 BenefitsClarity of expectations before coding startsEnhances confidence when refactoringTests acts as documentation
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
Security Sanitizing html & sanitize module
JSON Vulnerability – Redefining Array Constructor
XSRF
Strict Contextual EscapingSCE 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 easierc) from v1.2, sce is enabled by defaultd) whitelisting or blacklisting urls for sce to configure trusted
context using module config and $sceDelegateProvider
3.Anatomy
Anatomy of an AngularJS application – Understanding structure of an Angular app with basic & advanced examples
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)
Workflow - AngularJS Load AngularJS
Bootstrap or Invoke
Declare Relationship
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js" />
<html ng-app> or <div ng-app>
ng-model="modelName"{{modelName}}
Taxonomy Scopes
Models
Controllers
Services
Directives
Modules
Filters
Factories
Templates
Routes
Animations
Validators
Providers
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
Basics – Example
Creating View & Controller
Using Directive & Data Binding
<html ng-app>
<script>
function SimpleController($scope) {
$scope.name = "First Last";
}
</script>
<body>
<div class="container" ng-controller="SimpleController">
Name: <input type="text" ng-model="name" /> <br />
{{ name }}
</div>
</body>
</html>
<div class="container" ng-controller="SimpleController"><h3>Adding a Simple Controller</h3><ul>
<li ng-repeat="cust in customers">{{ cust.name }} - {{ cust.city }}
</li></ul>
</div><script>
function SimpleController($scope) {$scope.customers = [
{ name: 'Anuj Malik', city: 'Bengaluru' },{ name: 'Deepak Kumar', city: 'Mumbai' }];
}</script>
Basics – Another Example Repeating
withng-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
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"
});
AdvancedForms
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
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
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 heredeferred.resolve(data);
}).error(function (error){// error handlingdeferred.reject();
});}, 2000);deferred.promise.then(function(data){
$scope.customers = data;});
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
Modules – The Containers
<html ng-app="moduleName">
Factory
Service
Provider
Value
Filter
View Controller
*FactoryDirectives
Routes
Module
Config
$scope
Modules – Example Creating
Creating Controller
Define Routes
var demoApp = angular.module('demoApp', []);var demoApp = angular.module('demoApp', ['ngRoute']);
demoApp.controller('SimpleController', function ($scope) {$scope.customers = [{ name: 'Akhil', city: 'Bengaluru' },
{ name: 'Ankit', city: 'Mumbai' }];});
demoApp.config(function ($routeProvider) {$routeProvider
.when('/',{controller: 'SimpleController',templateUrl:'View1.html'})
.when('/view2',{controller: 'SimpleController',templateUrl:'View2.html'})
.otherwise({ redirectTo: '/' });});
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();});
4.Demos
Get familiar with wide range of demos on different aspects of AngularJS as well as complete apps & opensource projects
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
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
5.Directives
Extend HTML with directives for your application specific functionality, abstracted into a reusable & clean interface
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>
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
ExecutionSeq 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.
Transcludefunction 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 transcludedchild content has not been linked in yet.
Transcludefunction 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-linkCompiled DOM element is available but should not be modified because child directive DOM elements have not been linked in yet.
Transcludefunction 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
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;}
}; };
}]);
Built-In Directives App, Controller, Include & Init
ng-app="plaintext" ng-controller="plaintext" ng-include="string"|<ng-include
src="string" onload="expression" autoscroll="expression">
ng-init="expression"
Model & Binding ng-model="expression" ng-bind[-html-unsafe]="expression" ng-bind-
template="string{{expression}}string{{expression}}"
ng-non-bindable ng-bind-html="expression"
Styling & Image ng-class[-even|-odd]="string|object" ng-style="string|object" ng-hide|show="boolean" ng-disabled="boolean"
ng-src="string"
Condition & Flow ng-repeat="([key,] value) in object|array" ng-switch="expression"|<ng-switch
on="expression">
ng-if="expression“
Events ng-[mousedown, mouseenter,
mouseleave, mousemove, mouseover, mouseup]="expression"
ng-[keydown, keyup, keypress]="expression"
ng-[copy, cut, paste]="expression“ ng-[focus, blur]="expression" ng-[dbl]click="expression" ng-change="expression" ng-submit="expression"
Form Control <form|ng-form name="plaintext"> | ng-
form="plaintext" ng-checked="boolean" ng-href="plaintext{{string}}"
https://docs.angularjs.org/api/ng#directive & https://www.cheatography.com/proloser/cheat-sheets/angularjs/
6.Testing & Debugging
How AngularJS helps in creating testable application and what tools are available for testing & debugging your app
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
Testing – Unit Tests Installing Karma & Jasmine
Use npm to install karma, jasmine etc
Karma command line to run directly or configure npmtest script
Jasmine behavior driven testing included matchers toBe
and toEqual, toMatch, toBeDefined, toBeUndefined, toBeNull, toContain, toBeLessThan, toBeGreaterThan, toThrow
custom matchers
npm install karma --save-devnpm install -g karma-clinpm install karma-jasmine –save-devnpm install karma-chrome-launcher --save-dev
karma init karma.conf.jskarma 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);
});});
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 functionreturn service.user_id;
}
Angular Batarang – Chrome extension that acts as a debugging tool for Angular apps
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.
Further reading Sites https://docs.angularjs.org/tutorial http://yeoman.io/ https://builtwith.angularjs.org/ http://angular-ui.github.io/ http://cmaurer.github.io/angularjs-nvd3-directives/ https://www.dashingd3js.com/d3-resources/d3-and-angular
Training https://www.codeschool.com/courses/shaping-up-with-angular-js https://egghead.io/
Books ng-book AngularJS AngularJS in Action AngularJS Directives
References https://github.com/lukehoban/es6features http://blog.teamtreehouse.com/7-web-development-
trends-for-2015 https://www.nginx.com/blog/time-to-move-to-a-four-
tier-application-architecture/ http://www.slideshare.net/jgzheng/web-application-
landscape https://www.keycdn.com/blog/web-development-
tools/ https://arc.applause.com/2016/05/24/progressive-
web-apps/ http://blog.swazza.io/posts/reactive-ui-ng2 http://www.bradoncode.com/blog/2015/05/19/karma-
angularjs-testing/
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
Thanks!Any questions?
You can find me at:@[email protected]
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