Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

AngularJS Anatomy & Directives

6,923 views

Published on

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.

Published in: Technology

AngularJS Anatomy & Directives

  1. 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. 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. 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. 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. 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. 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. 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. 8. 2. Concepts Angular combines lot of good programming concepts together to create an effective & powerful web app development framework
  9. 9. 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>
  10. 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. 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. 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
  13. 13. 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
  14. 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. 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
  16. 16. Data Binding Illustration  Scope is basically acting as the ViewModel which enables two way data binding
  17. 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. 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. 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. 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. 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. 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. 23. 3. Anatomy Anatomy of an AngularJS application – Understanding structure of an Angular app with basic & advanced examples
  24. 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)
  25. 25. 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}}
  26. 26. Taxonomy  Scopes  Models  Controllers  Services  Directives  Modules  Filters  Factories  Templates  Routes  Animations  Validators  Providers
  27. 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
  28. 28. 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>
  29. 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. 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. 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. 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. 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. 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. 35. Modules – The Containers <html ng-app="moduleName"> Factory Service Provider Value Filter View Controller *FactoryDirectives Routes Module Config $scope
  36. 36. 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: '/' }); });
  37. 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. 38. 4. Demos Get familiar with wide range of demos on different aspects of AngularJS as well as complete apps & opensource projects
  39. 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. 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. 41. 5. Directives Extend HTML with directives for your application specific functionality, abstracted into a reusable & clean interface
  42. 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. 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. 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. 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; } }; }; }]);
  46. 46. 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{{exp ression}}"  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/
  47. 47. 6. Testing & Debugging How AngularJS helps in creating testable application and what tools are available for testing & debugging your app
  48. 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. 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. 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. 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.
  52. 52. 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
  53. 53. 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/
  54. 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. 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

×