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.

Angular1x and Angular 2 for Beginners

1,588 views

Published on

This fast-paced overview for beginners discusses some aspects of AngularJS 1.x and 2.x, which versions to learn (and why), and the technologies that you need to learn. We'll delve into examples of combining AngularJS with other technologies (such as BackboneJS and D3.js), and also address the +/- of AngularJS.

Published in: Technology
  • Be the first to comment

Angular1x and Angular 2 for Beginners

  1. 1. Angular 1.x and 2 for Beginners Oswald Campesato Consultant/Training: www.iquarkt.com ocampesato@yahoo.com SVCC 2015 (10/03/2015) Evergreen College San Jose
  2. 2. Main Topics in This Session Features of Angular 1.x What about Angular 2 What about BB/D3/AngularJS What to Learn….?
  3. 3. Brief History of Angular Misko Hevery (the creator) Began in 2009 An open source project (Google) Client-side framework for Web apps Distributed core team Initially meant primarily for UI designers Lots of modules available Evolved in functionality and complexity Six years is a long time (hence Angular 2)
  4. 4. Some Features of Angular 1.x  MV* pattern, modular code, expressive HTML  “hockey stick” learning curve  Two-way data binding  Works with BackboneJS (no directive required)  Works with ReactJS and D3.js (custom directives)  built-in services and support for custom services
  5. 5. What are Angular Directives? Angular built-in directives extend HTML Appear as an “ng-” prefix (or data-ng- prefix) ng-app, ng-controller, ng-model ng-click, ng-show, ng-enable Angular custom directives: written by you
  6. 6. Simple Example of Angular 1.x <!DOCTYPE html>  <html ng-app>  <head>  <script  src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.4/an gular.min.js">  </script>  </head>  <body>  Type something: <input type="text" ng-model="sometext" />  <h1>Hello {{ sometext }}</h1>  <h1>Hello again {{ sometext }}</h1>  </body> </html>
  7. 7. Services in Angular 1.x  <html ng-app=“app”>  var app = angular.module(“app”, []);  Controllers: app.controller(“myController”, function() { });  Directives: app.directive(“myDirective”, function() { });  Factories: app.factory(“myFactory”, function() { });  Services: app.service(“myService”, function() { });  Providers: app.provider(“MyProvider”, function() { });
  8. 8. Click Events in Angular 1.x  <!DOCTYPE html>  <html ng-app=“app”>  <head><script src=…></script>  <script>  var app = angular.module(”app", []);  </script>  </head>  <body>  <button ng-click="count = count + 1" ng-init="count=3">  Increment the count  </button>  count: {{count}}  </body>  </html>
  9. 9. Scope in Controller in Angular 1.x: AVOID  <!DOCTYPE html>  <html ng-app=“app”>  <head><script src=…></script></head>  <body>  <div ng-controller=”MyController">  <p>{{food}}</p>  </div>  <script>  var app = angular.module('app', []);  app.controller(”MyController", function($scope){  $scope.food = “Chicago pizza”;  });  </script>  </body>  </html>
  10. 10. Best Practice: Controller As in Angular 1.3+  <!DOCTYPE html>  <html ng-app=“app”>  <head><script src=…></script></head>  <body>  <div ng-controller=”MyController as vm">  <p>{{vm.value}}</p>  </div>  <script>  var app = angular.module('app', []);  app.controller(”MyController", function(){  var vm = this;  vm.value = “stuffed pizza”;  });  </script>  </body></html>
  11. 11. Best Practice: Controller As in Angular 1.3+  <!DOCTYPE html>  <html ng-app=“app”>  <head><script …></script></head>  <body>  <div ng-controller="ButtonController as bc">  <button ng-click="bc.clickMe()">Click Me</button>  </div>  <script>  var app = angular.module('app', []);  app.controller("ButtonController", function(){  var bc = this;  bc.clickMe = function() { alert("Hello World"); }  });  </script></body>  </html>
  12. 12. Angular Factory Example (part 1)  <div ng-controller="MainCtrl as mc">  <input type="text" placeholder="Enter a Word:” name="name"  ng-model="mc.word" required />  <input type="submit" name="submit" value="Save”  ng-click='mc.saveItem()')  </div>  <script>  var app = angular.module("app", []);  app.controller("MainCtrl", function(db) {  var mc = this;  mc.word = "";  mc.saveItem = function() {  db.addItem(mc.word);  mc.word = "";  };
  13. 13. Angular Factory (part 2)  app.factory('db', function() {  var items = [];  var dao = {};  dao.addItem = function(item) {  items.push(item);  return 'added item';  };  dao.getItems = function() {  return items;  }  // a factory must return an object:  return dao;  });
  14. 14. Angular $http Service $http.get('https://api.github.com/users/johndoe') .success(function(data) {  $scope.gists = data; }) .error(function(data, status) {  console.error('Repos error', status, data); }) .finally(function() {  console.log("finally finished repos"); });
  15. 15. Custom Directive in Angular 1.x  <!DOCTYPE html>  <html ng-app=“app”>  <head><script …></script></head>  <body>  <hello-world></hello-world>  <script>  var app = angular.module(”app", []);  app.directive('helloWorld', function() {  return {  //restrict: 'AE', // A, E, C, or M  template: '<h3>Hello World from SVCC</h3>’  };  });  </script>  </body></html>
  16. 16. D3 Directive in Angular 1.x (outline)  <body>  <my-cube></my-cube>  <script>  var app = angular.module(”app", []);  app.directive('myCube', function() {  function link(scope, el, attr) {  // ADD YOUR CUSTOM D3 CODE HERE  }  // return an object to modify the DOM  return {  link: link,  restrict: 'E'  }  });  </script></body></html>
  17. 17. D3 Code for a Cube (part 1)  // ADD YOUR CUSTOM D3 CODE HERE  var width = 300, height = 300, fillColors = ["red", "yellow", "blue"];  var points1 = "50,50 200,50 240,30 90,30";  var points2 = "200,50 200,200 240,180 240,30";  // “outer” SVG element (contains the cube):  var svg = d3.select(el)  .append("svg")  .attr("width", width)  .attr("height", height);  // top face (parallelogram):  var polygon = svg.append("polygon")  .attr("points", points1)  .attr("fill", fillColors[1])  .attr("stroke", "blue")  .attr("stroke-width", 1);
  18. 18. D3 Code for a Cube (part 2)  // front face (rectangle)  svg.append("rect")  .attr("x", 50)  .attr("y", 50)  .attr("width", 150)  .attr("height", 150)  .attr("fill", fillColors[0]);  // right face (parallelogram)  var polygon = svg.append("polygon")  .attr("points", points2)  .attr("fill", fillColors[2])  .attr("stroke", "blue")  .attr("stroke-width", 1);
  19. 19. Custom Directive Options in Angular 1.x  app.directive('helloWorld', function() {  return {  //omitting “restrict” and “template”  templateUrl: 'SomeMarkup.html',  controller: MyControllerFunction,  controllerAs: ctrl,  bindToController: true,  transclude: true, // overwrite versus include  compile: compileFunction, // before DOM insertion  link: linkFunction, // after DOM insertion  scope: {  oneWay: ‘@’, twoWay: ‘=‘, expr: ‘&’  }  };  });
  20. 20. Two-way Data Binding  Model update causes view update  View update causes model update  Angular checks what has changed  Angular also checks what might have changed  Synchronizing view+model an be inefficient  Can lead to “infinite” loops ;(
  21. 21. Best Practice: “One-time” Checking  A feature of Angular 1.3 (or higher): {{::firstname}} is Angular 1.3+ syntax  forAngular 1.2: use the bindonce module  Eliminates redundant checks (better performance)
  22. 22. What about BackboneJS?  BackboneJS provides built-in objects:  A View object  A Model object  A Collection object  A Collections object
  23. 23. Backbone and Angular 1.x (part 1)  <body ng-controller="MyController as ab">  <ul><li ng-repeat="item in ab.collection.models">  {{ item.name }}  <input type="number" ng-model="item.attributes.cost">  </li></ul>  <p>Total Cost: {{ ab.collection.totalCost() | currency }}</p>  <script>  var app = angular.module('app', []);  app.controller('MyController', function() {  var ab = this;   var data = [  { id: 1, name: 'Beer', cost: 10, quantity: 3 },  { id: 2, name: 'Pizza', cost: 20, quantity: 5 },  { id: 3, name: 'Chips', cost: 15, quantity: 2 }  ];
  24. 24. Backbone and Angular 1.x (part 2)  var FoodCollection = Backbone.Collection.extend({  totalCost: function() {  var total = 0;  this.forEach(function(model) {  total += model.get('cost')*model.get('quantity');  });  return total;  }  });  ab.collection = new FoodCollection(data);  ab.items = ab.collection.toJSON();  });  </script>
  25. 25. AngularJS + Other Technologies AngularJS + Backbone AngularJS + ReactJS AngularJS + Firebase AngularJS + Parse AngularJS + Pubnub AngularJS + Material Design UP NEXT: DELVING INTO ANGULAR 2…..
  26. 26. Features of Angular 2 (part 1) ETA: Q1/Q2 of 2015 + component-based architecture + loosely coupled components + less code more application focus + "Mobile First" approach Angular 2 Github repository: https://github.com/angular/angular
  27. 27. Features of Angular 2 (part 2) Angular 2 can be 5x faster than Angular 1.x One-way data binding (by default) Two-way data binding (optional) Dependency injection Support for ES6 and TypeScript Performance comparable to React(?)
  28. 28. Ang1.x features dropped from Ang 2 + $scope + factories + controllers + providers + $apply + $digest + many built-in directives
  29. 29. Angular 2 Template Syntax  [attribute] syntax: <input [value]="name”>  (method) syntax: <input #myname (keyup)=”vm.myCtrlMethod()">  ^ symbol handles bubble up events: <div (^click)=”handleClick()"> <div></div> </div>  [(method)] syntax for two-way binding: <input [(ng-model)]=”vm.foo”> <p>Hello {{vm.foo}}</p>
  30. 30. Ang 1.x ng-repeat vs *ng-for  Angular 1.x “ng-repeat”: <ul> <li ng-repeat="user in users"> <h2>{{user.name}}</h2> </li> </ul>  Angular 2 “*ng-for”: <ul> <li *ng-for="#user in users"> <h2>{{user.name}}</h2> </li> </ul>
  31. 31. The APIs of a DOM Element  Attributes: hold values in elements (always strings)  Properties: properties of a DOM object  Methods: the functions on a DOM object  Events: click, focus, input, etc  Attributes and properties sometimes match: The ‘src’ attribute of an <img> element  Attributes and properties sometimes do not match: <input value="pizza"> input.value = "beer"; input.getAttribute('value'); // "pizza”  NB: Ang 2 binds to properties; Ang 1.x binds to attributes
  32. 32. What are Transpilers?  They convert code from one language to another  Babel (formerly 6to5): +converts ES6 (some ES7) to ECMA5 + appears to be the de facto standard  Traceur (Google): + converts ES6 to ECMA5 + used by Angular 2 TypeScript (MicroSoft): http://www.TypeScriptlang.org
  33. 33. Angular 2 and ES6 ES6 classes (transpiled to ES5) @ symbol for annotations @Template @Component
  34. 34. Angular 2 + ES6 Example import {Component, Template, bootstrap} from 'angular2/angular2'; @Component({ selector: 'my-app' }) @Template({ inline: '<h1>Hello {{ name }}</h1>' }) class MyAppComponent { // component controller constructor() { this.name = 'World!'; } } bootstrap(MyAppComponent);
  35. 35. Angular 2 and Event Objects  <button (click)="clicked($event)"></button> @Component(...) @View(...) class MyComponent { clicked(event) { event.preventDefault(); // do stuff here } } bootstrap(MyComponent);
  36. 36. Angular 2 and Forms (part 1)  import {Component, Template, Parent} from 'angular2/angular2'  import {FormBuilder, Validators, FormDirectives, ControlGroup} from 'angular2/forms’;  @Component({  selector: 'login-page'  })  @Template({  url: 'pages/login.html',  directives: [View, FormDirectives]  })
  37. 37. Angular 2 and Forms (part 2)  export class LoginPage {  constructor() {  var fb = new FormBuilder()  this.loginForm = fb.group({  email: ['', Validators.required],  password: ['', Validators.required],  });  }  doLogin(event) {  // Show the value of the form  console.log(this.loginForm.value);  event.preventDefault();  }  }
  38. 38. Angular 2 and Forms (part 3)  <form (^submit)="doLogin($event)" [control-group]="loginForm">  <div>  <input control="email" type="email” placeholder="Your email">  </div>  <div>  <input control="password" type="email" placeholder="Your email">  </div>  <button type="submit">Log in</button>  </form>
  39. 39. Angular2/Webpack Starter https://github.com/angular-class/angular2-webpack-starter  1) download zip file (or clone repo)  2) npm start (= "npm run server")  3) go to http://localhost:3000  Check out these files:  src/app/app.ts  src/app/bootstrap.ts
  40. 40. More Useful Links  Change detection in Angular 2: https://github.com/angular/watchtower.js http://zone.js/ http://victorsavkin.com/post/110170125256/change- detection-in-angular-2  Angular scaffolding: https://github.com/DaftMonk/generator-angular-fullstack https://github.com/yeoman/generator-angular http://lauterry.github.io/ngTailor/  Touch animations: https://docs.google.com/document/d/16Z6Lun15DoWNr E2imk7N-2WiRAaqc954LOfU2- 2JSoI/edit#heading=h.rcjxs836qiki
  41. 41. Angular Tutorials  Getting started with Angular 2: https://docs.google.com/document/d/1MkpvTNfmxHwd Sv9rQyQIvjRLnoGk4rvkNMkOEWTPkCw/edit#heading=h.6 z1yv9f94fuv  Building Angular Apps using Flux: https://docs.google.com/document/d/16axBamHEZORS_ KJZDjahLuhkhUuNVt77ZcGRoRiyjfQ/edit New features in Angular 1.4:  https://docs.google.com/document/d/1BkDxdkzB5Jm QBgpLKEkGY92pWF9Xr89cSLltPJVdHC0/edit
  42. 42. Future Work in Angular 2 Server-side rendering Web Workers smooth and responsive UI Native mobile UI (see Ionic for mobile) Compile as build step
  43. 43. What about ES6? Arrow functions and let keyword Block scopes Classes and inheritance Default parameters Destructured assignment Generators, Iterators, Maps, and Sets Promises and Rest parameters Spread operator Template Literals
  44. 44. ES6 let and Arrow Functions let square = x => x * x; let add = (x, y) => x + y; let pi = () => 3.1415; console.log(square(8)); // 64 console.log(add(5, 9)); // 14 console.log(pi()); // 3.1415
  45. 45. ES6 Class Definition (part 1) class Rectangle { constructor(height, width) { this.height = height; this.width = width; } calcArea() { return this.height * this.width; } }  var r1 = new Rectangle(5,10);  var r2 = new Rectangle(25,15);
  46. 46. ES6 Class Definition (part 2)  console.log(“r1 area = ”+r1.calcArea());  console.log(“r2 area = ”+r2.calcArea());  Test this code here: http://babeljs.io/repl/  More Examples: https://developer.mozilla.org/en- US/docs/Web/JavaScript/Reference/Classes
  47. 47. What is TypeScript?  A superset of JavaScript (ES6): 10/01/2012  A compiled language (tsc compiler)  strong typing and also type inferencing  Type checking during compile time  “minimal” extra compile time overhead  “.ts” files are transpiled into “.js” files (via tsc)  “lib.d.ts” contains TypeScript definitions  TypeScript type definitions (update via “nuget”): https://github.com/borisyankov/DefinitelyTyped
  48. 48. TypeScript Variables  var isDone: boolean = false;  var height: number = 6;  var name: string = "dave";  var myList:number[] = [1, 2, 3]; // option #1  var myList:Array<number> = [1, 2, 3]; // option #2  var changeMe: any = 4;  changeMe = ”I’m a string now";  var myList:any[] = [1, true, ”pizza"];
  49. 49. TypeScript Functions  void return type: function myLogger(msg?:string): void { console.log("My custom logger: “+msg); }  Generics: function identity<T>(arg: T): T { return arg; } // output has 'string' type (explicit/inferred): var output = identity<string>("Dave"); var output = identity("Dave");
  50. 50. TypeScript ‘any’ Type  any return type:  function selectSomething(x): any {  if (typeof x == "object") {  return 10;  } else {  return "abc";  }  } NB: “any” type disables type checking NB: you can disallow implicit “any” in Visual Studio
  51. 51. Functions versus Lambda Expressions  JavaScript Function: var doubleJS = function(x) { return 2*x; }  TypeScript Function: var doubleTS = function(x:number) {return 2*x;}  Lambda versions of the TypeScript function: var lambdaTS = (x:number) => 2*x; var lambdaTS = x => 2*x; Another Lambda function: var x = function(delay:number, () =>void) { // timer code });
  52. 52. TypeScript Interfaces interface User { name: string; weight?: number; // optional } function displayUser(user: User) { console.log(user.name); }  This works even without ‘weight’ in the interface: var aUser = {name: "John Smith", weight:200}; displayUser(aUser);
  53. 53. TypeScript Class (part 1) class User { fname: string; lname: string; constructor(fname:string, lname:string) { this.fname = fname; this.lname = lname; } fullname():string { return this.fname+" "+this.lname; } }
  54. 54. TypeScript Class (part 2)  var u1:User, u2:User;  u1 = new User("Jane", "Smith");  u2 = new User("John", "Jones");  console.log("user1 = "+u1.fullname());  console.log("user2 = "+u2.fullname());  Exercise: use an interface in class User  Aside: use interfaces as arguments of public methods (whenever possible) instead of using standard JS/TS types or class instances
  55. 55. Convert JSON Data to TS Class (1) Consider the following array of data: var people = [ {fname:"Jane",lname:"Smith",zip:"94043"}, {fname:"John",lname:"Jones",zip:"94539"}, {fname:"Dave",lname:"Starr",zip:"67800"} ]
  56. 56. Convert JSON Data to TS Class (2) class People {  public fname:string;  public lname:string;  public zip:string;  constructor(public fname:string,  public lname:string,  public zip:string) {  this.fname = fname;  this.lname = lname;  this.zip = zip;  } }
  57. 57. Convert JSON Data to TS Class (3) Array of TypeScript objects: var TSPeople = [ new People("Jane","Smith","94043"), new People("John","Jones","94539"), new People("Dave","Starr","67800") ];
  58. 58. TypeScript and the this keyword  The this keyword is contextually bound in the same fashion as standard JS functions  The this keyword is lexically bound in Lamba functions so it’s automatically captured (emitted JS uses _this)  Typically based on how the function is called  More information about the this keyword: https://tinyurl.com/MDNthis
  59. 59. Migrating JS ‘classes’ to TypeScript  Option #1: Annotate with an interface: +Interface and impl are synchronized manually +Faster initially and lower risk  Option #2: Refactor as a class: +More initial code changes +More maintainable and semantic http://www.typescriptlang.org/Handbook
  60. 60. What about Aurelia?  Similar to Angular 2 and created by Rob Eisenberg: http://aurelia.io/  Blog post: http://www.syntaxsuccess.com/viewarticle/angular- 2.0-vs-aurelia  Code sample: http://www.syntaxsuccess.com/articleList/aurelia
  61. 61. What Should I Learn???  Main features of ES6 and TypeScript 1.5+  “basic” Angular 1.4 and 2 (best practices)  Practice converting code from ANG 1.x to 2  Select an IDE: +WebStorm 10: free 30-day trial ($49/year) +Visual Studio Code (free) + Atom (free) with atom-TypeScript extension  Command Line Tools: + npm, npmjs, gulp, grunt (older), broccoli, + webpack, browserify (older), jspm+systemjs https://github.com/addyosmani/es6-tools
  62. 62. Other Technologies to Learn  Sass/Bootstrap 4 (previous: less)  HandleBars/Nunjucks (previous: Jade/EJS)  Material Design (and MDL)  Firebase/AngularFire  D3.js for Data Visualization  Ionic (=Angular for Mobile)
  63. 63. Browser Status for ES6  Modern IE: https://goo.gl/56n7IL  Mozilla: https://goo.gl/iSNDf9  Chrome: https://www.chromestatus.com/features#ES6
  64. 64. Useful ES6 Links https://github.com/lukehoban/es6features http://kangax.github.io/compat-table/es6/ https://dev.modern.ie/platform/status/?filter=f3f0000bf&search=es6 https://developer.mozilla.org/en- US/docs/Web/JavaScript/New_in_JavaScript/ECMAScript_6_suppo rt_in_Mozilla https://medium.com/@bojzi/overview-of-the-javascript-ecosystem- 8ec4a0b7a7be
  65. 65. What about ReactJS? Provides “V” in MVC One-way data binding JSX (optional) Hierarchical set of components “React” = top-level namespace Maintains a “virtual DOM” Only updates the “delta” Hence it’s very efficient
  66. 66. What about EmberJS 2.0? Learning curve Two-way data binding MVC pattern Involves accessors (“get”) involves mutators (“set”)
  67. 67. People to follow  Addy Osmani: http://www.super-script.us/2015/es6-tools.html  Nicolas Bevacqua: http://ponyfoo.com/  Dr. Axel Rauschmeyer: http://www.2ality.com/  Mike North: https://frontendmasters.com/
  68. 68. Web Components Meetup  This meetup is currently at HackerDojo in MTV: http://www.meetup.com/Web-Components-Silicon- Valley-Meetup/
  69. 69. Github + Graphics Samples  https://github.com/ocampesato/reactjs-graphics  https://github.com/ocampesato/angular-graphics  https://github.com/ocampesato/web-animations  https://github.com/ocampesato/polymer-svg-css3
  70. 70. Recent/Upcoming Books and Training 1) HTML5 Canvas and CSS3 Graphics (2013) 2) jQuery, CSS3, and HTML5 for Mobile (2013) 3) HTML5 Pocket Primer (2013) 4) jQuery Pocket Primer (2013) 5) HTML5 Mobile Pocket Primer (2014) 6) D3 Pocket Primer (2015) 7) Python Pocket Primer (2015) 8) AngularJS Pocket Primer (2016)

×