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.
Dev Dives: Streamline document processing with UiPath Studio Web
Angular Beginners Guide
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. Main Topics in This Session
Features of Angular 1.x
What about Angular 2
What about BB/D3/AngularJS
What to Learn….?
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. 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. 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
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. 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. 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. 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. 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. 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. 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. What about BackboneJS?
BackboneJS provides built-in objects:
A View object
A Model object
A Collection object
A Collections object
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. AngularJS + Other Technologies
AngularJS + Backbone
AngularJS + ReactJS
AngularJS + Firebase
AngularJS + Parse
AngularJS + Pubnub
AngularJS + Material Design
UP NEXT: DELVING INTO ANGULAR 2…..
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. 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. Ang1.x features dropped from Ang 2
+ $scope
+ factories
+ controllers
+ providers
+ $apply
+ $digest
+ many built-in directives
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. 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. 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. Angular 2 and ES6
ES6 classes (transpiled to ES5)
@ symbol for annotations
@Template
@Component
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. Angular 2 and Event Objects
<button (click)="clicked($event)"></button>
@Component(...)
@View(...)
class MyComponent {
clicked(event) {
event.preventDefault();
// do stuff here
}
}
bootstrap(MyComponent);
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. 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();
}
}
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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. Browser Status for ES6
Modern IE: https://goo.gl/56n7IL
Mozilla: https://goo.gl/iSNDf9
Chrome: https://www.chromestatus.com/features#ES6
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. What about EmberJS 2.0?
Learning curve
Two-way data binding
MVC pattern
Involves accessors (“get”)
involves mutators (“set”)
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. Web Components Meetup
This meetup is currently at HackerDojo in MTV:
http://www.meetup.com/Web-Components-Silicon-
Valley-Meetup/
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)