1 / 56

AngularJS Introduction

Richard Johnson Goal Designs Inc. AngularJS Introduction. GDG Twin Cities Meetup – May 1, 2013 Slides available: http:// goaldesigns.com /presentations-2013 rjohnson@ goaldesigns.com. AngularJS – Where?. Cloud. Web Server. Web browser. Web Apps. AngularJS – Client. Cloud.

eithne
Download Presentation

AngularJS Introduction

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Richard Johnson Goal Designs Inc. AngularJS Introduction GDG Twin Cities Meetup– May 1, 2013 Slides available: http://goaldesigns.com/presentations-2013 rjohnson@goaldesigns.com

  2. AngularJS – Where? Cloud Web Server Web browser Web Apps

  3. AngularJS – Client Cloud Web Server Web browser Web Apps

  4. First Example - jQuery <!doctype html> <html> <head> <script src="http://code.jquery.com/jquery-1.9.1.min.js"></script> <script type="text/javascript"> $(function() { $("#yourName").keyup(function () { $("#helloName").text("Hello " + this.value + "!"); }); }); </script> </head> <body> <div> <label>Name:</label> <input type="text" id="yourName"> <hr> <h1 id="helloName"></h1> </div> </body> </html>

  5. jQuery • Simplifies event binding and DOM manipulation • Common API across multiple browsers • Supports plug-in modules to extend functionality • Requires writing JavaScript code to wire

  6. First Example - AngularJS <!doctype html> <html ng-app> <head> <script src="https://ajax.googleapis.com/ajax/libs/ ⬋ angularjs/1.0.6/angular.min.js"></script> </head> <body> <div> <label>Name:</label> <input type="text" ng-model="yourName"> <hr> <h1>Hello {{yourName}}!</h1> </div> </body> </html>

  7. Imperative vs. Declarative • Compare jQuery imperative wiring • to AngularJS declarative relationships <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>

  8. Abstractions • jQuery abstracts browser functionality • e.g. DOM traversal, event binding • AngularJS abstracts relationships (and more)

  9. Browser base • AngularJS, and all web apps, are built on browser functionality • Must use the technologies of the web • HTML • CSS • JavaScript

  10. The DOM abstraction • HTML is a declarative document language • Browser translates HTML into a Document Object Model (DOM) • DOM is the browser’s in-memory document representation • JavaScript can manipulate the DOM

  11. AngularJS “compiles” HTML • Browsers send a document (i.e. DOM) ready event • AngularJS can intercede and rewrite the DOM • The rewrite is driven by markup in the DOM

  12. Model-View-Controller (MVC) • Software architectural pattern • Separates display from data • Originated with Smalltalk programmers • From work at Xerox PARC in the late 70’s • Models represent knowledge • Views provide a (visual) representation of attached model data • Controllers connect to and control views and models

  13. MVC and Variations • Different variations of the pattern • Model-View-ViewModel (MVVM) • Model-View-Presenter (MVP) • Variations differ on… • … connectivity • … cardinality • … directionality

  14. Model-View-Whatever “MVC vs MVVM vs MVP. What a controversial topic that many developers can spend hours and hours debating and arguing about.For several years AngularJS was closer to MVC (or rather one of its client-side variants), but over time and thanks to many refactorings and api improvements, it's now closer to MVVM – the $scope object could be considered the ViewModel that is being decorated by a function that we call a Controller. … I hereby declare AngularJS to be MVW framework - Model-View-Whatever. …” Igor Minar – Google AngularJS Development Team

  15. Alternative MV* Frameworks • Backbone.js • Ember.js • Knockout • Others • Summary from 2012 Throne of JS conference

  16. Library vs. Framework • Library (Backbone and Knockout) • passive functionality • invoked by the application • Framework (Ember) • provides application architecture • handles common requirements • invokes application code • AngularJS is closer to a framework

  17. TodoMVC - comparison of MV* frameworks

  18. One (biased?) data point • *I ported my Backbone application to angular. The Code size went down from 5k lines of code to guess what? 750 lines. Not just that.. The code is much cleaner.. Earlier, there was a huge technical debt attached to this implementation in backbone.. Each time I had to sit with it. It took me quite a while to understand all the hooks and how the individual models and classes and views interacted together.. ..Now its a breeze.. * • http://stackoverflow.com/a/10264263

  19. My AngularJS Discovery • Working with AJAX in mid-2011 • XML for data • XSLT to map XML data to HTML • Considered changing to JSON • Found a link to AngularJS(alpha)

  20. Getting started • AngularJS website: angularjs.org • Examples are live • Phonecat tutorial is worthwhile • My “goto” sources: • Developer guide • API reference

  21. What Makes an AngularJS App? • Load AngularJS <script src="https://ajax.googleapis.com/ajax/libs/ angularjs/1.0.6/angular.min.js"></script> • Bootstrap <html ng-app> • Declare relationships ng-model="yourName” {{yourName}}

  22. Scope • One created with each controller • Prototypically inherits from parent • AngularJS has a root scope • Can create isolated scopes (e.g. in directive)

  23. Model data referenced by scope

  24. Scopes are nested

  25. 2-way Data Binding • Automatic propagation of data changes • Model is single source of truth • Digest cycle

  26. Controller • Contains the code behind the view • Try to keep lightweight

  27. Our early AngularJS example • Added to a WordPress site • Custom theme • Page templates with shortcodes • Built summer 2012 (just as AngularJS 1.0 shipped) • Created order form and product location pages Note – it’s a live site (and good wine ) • Too much code in the controller - modularize

  28. Forms • Provides declarative form validation • Input fields declared as: required, email • Form has flags for: $valid, $dirty • Usable as a standalone validation library

  29. Using Directives • Directives enhance HTML • Custom element name or attribute (also class and comment) • AngularJS provides over 50 • form – element directive • ng-repeat – attribute directive (it’s amazing!)

  30. Filters • Declarative way to • format displayed data • filter and sort data arrays

  31. Services • Software architectural components • Services provide data and compute • Exist across views • Depend on other services • AngularJS has 20+ • $http – service to communicate with servers

  32. Server Communication $http({method: ‘GET’, url: fetchUrl}) .success(function(data, status) { // process the data here }) .error(function(data, status) { // error handling }); • $http service • Input config object • Returns promise • Communication is asynchronous

  33. Promises • Promises represent result of an action • Particularly used with asynchronous actions • They are either resolved or rejected

  34. Dependency Injection (DI) • DI is a software architectural pattern • Separation of concerns • Service creation independent from usage • Good for • Modular code • Allows AngularJS to wire in correct order • Supports substitution (for patching and testing)

  35. DI and JavaScript Minification • Services identified by parameter name • Minification obfuscates the name • Pass names as strings in array angular.module('GoaleryServices') .factory('StatusManager', [ 'CloudLogin', '$q', function (cloudLogin, $q) { …

  36. AngularJS is pure JavaScript • Prototype-based scripting language • Dynamic, weakly typed, first-class functions • Great JavaScript book: • Crockford (2008) JavaScript: The Good Parts – O’Reilly

  37. Testing AngularJS Apps • JavaScript doesn’t have a compiler • Must execute code to test • Testability was a fundamental objective of AngularJS • MiškoHevery (AngularJS creator) • Previously created JsTestDriver

  38. AngularJS supports testing • Unit testing support • JsTestDriver • Jasmine • Karma • DI allows substituting mocks for hard to test code • Server communication • Logging • Angular Scenario Runner – E2E testing • Simulates user interations

  39. Building Web Apps • Single web page • Loads the base HTML and included sources once • App changes views dynamically • Server is called upon when needed • Prefer using asynchronous server calls • Data changes • Fetch more data

  40. Templates • Declarative view specification • HTML augmented with: • Directives, Markup, Filter, Form Controls • Loaded either • with a simple single web page • dynamically into a view as partials

  41. URL Routing • Define the mapping from URL to view • Can also bind controller • Define URL parameters $routeProvider.when('/Book/:bookId', { templateUrl: 'book.html', controller: BookCntl }); $routeProvider.when('/Book/:bookId/ch/:chapterId', { templateUrl: 'chapter.html', controller: ChapterCntl });

  42. Deep Linking • AngularJS navigation updates the browser address bar • Uses the HTML5 history API – fallback to hash-bang (#!) URL • Users can link to pages in you app • Server must recognize the link pattern and serve the application

  43. Creating Directives • Directives package reusable HTML • Naming nuance: “myDir” becomes “my-dir” • Conceptual compile and link phases • Can specify: scope, binding, restrictions, etc • Supports transclusion • Consider creating a custom DSL

  44. Modules • Packaging of JavaScript code • Modules declare dependencies • AngularJS instantiates in correct order • Provides separation of namespaces

  45. AngularJS • Open source – MIT License • Built by Google and community • 1.0 released June 2012 • 1.0.6 current (April 2013) • http://angularjs.org/

  46. Versions • AngularJS 1.0.X are considered stable production releases • Contains bug fixes and documentation updates • AngularJS 1.1.X is unstable development • Next stable feature release will be 1.2.X • Available on the Google CDN • https://ajax.googleapis.com/ajax/libs/angularjs/1.0.6/angular.js • Both full source and minified (angular.min.js)

  47. jQuery integration • AngularJS includes a jQuery “lite” • Provides the minimal features directly used • Including jQuery will be used instead • Note – jQuery must be included before AngularJS

  48. Browser support • Chrome • Internet Explorer 9+ (others see next slide) • Firefox • Safari • Opera • mobile browsers (Android, Chrome Mobile, iOS Safari)

  49. Internet Explorer 8 and earlier • IE 8 is officially supported and tested • Declare custom element tags • Routing uses #! mode (IE9 also has no HTML 5 history) • A few other XML namespace declarations • See http://docs.angularjs.org/guide/ie • IE 6 & 7 support is possible “in theory” • Google doesn’t test these versions • < 1% of U.S. browsers (March 2013)

  50. Tooling • Yeoman – workflow manager • Yo - scaffolding • Grunt - build • Bower - dependency management • Chrome debugger plugin (Batarang)

More Related