AngularJS - TechTalk 3/2/2014

53
TechTalk | 3 February 2014 Spyros Ioakeimidis

Transcript of AngularJS - TechTalk 3/2/2014

Page 1: AngularJS - TechTalk 3/2/2014

TechTalk | 3 February 2014 Spyros Ioakeimidis

Page 2: AngularJS - TechTalk 3/2/2014

AngularJS

❖ Seemed a bit weird in the beginning

❖ All these new terms and concepts…

!2

Page 3: AngularJS - TechTalk 3/2/2014

!3

Factories

Providers

Services

Controllers

Views

ModelsFilte

rs

Directives

ModulesDependency Injection

Promises

Page 4: AngularJS - TechTalk 3/2/2014

AngularJS

❖ Made for SPA (Single Page Applications)

❖ It has a learning curve!

❖ Maintained by Google (for some this is good, for others not)

❖ Community keeps increasing

!4

Page 5: AngularJS - TechTalk 3/2/2014

AngularJS

❖ MVC principle

❖ Others say it is an SPA framework

❖ Others that it is just a library to help you built a framework

❖ AngularJS is a toolset (extensibility)

!5

Page 6: AngularJS - TechTalk 3/2/2014

!6

Page 7: AngularJS - TechTalk 3/2/2014

Modules

!7

Page 8: AngularJS - TechTalk 3/2/2014

Modules❖ app = angular.module(‘myApp’, [])

❖ Use of an array to include other modules

❖ It is required when creating a new module (module declaration)

❖ app = angular.module(‘myApp’) retrieves an existing module (module reference)

❖ Modules cannot be included at runtime

!8

Page 9: AngularJS - TechTalk 3/2/2014

Modules❖ We have a module app

❖ .value()

❖ global values, good for defaults

❖ .constant()

❖ same as Value, but the it is expected to not change

❖ .service()

❖ .factory()

❖ .provider()

!9

Page 10: AngularJS - TechTalk 3/2/2014

MVC (or whatever…)

!10

Page 11: AngularJS - TechTalk 3/2/2014

W(M)VC❖ Whatever (Model)

❖ It is the $scope, which contains models and functions as well

❖ e.g. $scope.event = {‘title’: ‘Placed Event’}

❖ View

❖ HTML markup

❖ Controller

❖ An JS object

❖ app.controller(‘MyController’, function{})

❖ DOM manipulation does not belong to controllers

!11

Page 12: AngularJS - TechTalk 3/2/2014

Controller (Business Logic)

Directive (DSL in HTML)

Service (Library)

View (HTML)

Whatever (Data)

provides functionality

provides functionality

contains

communicates withstored in $scope of

!12

Hiller, Christopher. “Developing an AngularJS Edge.”

Page 13: AngularJS - TechTalk 3/2/2014

Scope.models

!13

Page 14: AngularJS - TechTalk 3/2/2014

Scope❖ prototypical inheritance

❖ treat scope as read-only in templates

❖ when binding to templates ng-model=“user.name”, always use a dot

❖ $rootScope

❖ $scope.$apply()

❖ $eval() -> $exceptionHandler(e) -> $digest()

❖ e.g. when observing DOM elements directly in directives

!14

Page 15: AngularJS - TechTalk 3/2/2014

❖ $scope.$watch(‘foo’, function() {})

❖ observe a model for changes, evaluates by reference

❖ will fire when $scope.foo = ‘’ and then $scope.foo = ‘bar’

❖ but not when $scope.foo.bar = ‘’ and then $scope.foo.bar = ‘baz’

❖ can evaluate by value (expensive operation!)

❖ when writing own $watch, it must be fast and it must be idempotent

!15

Scope

Page 16: AngularJS - TechTalk 3/2/2014

❖ $scope.$digest()

❖ $scope.$eval()

❖ $scope.{$on, $broadcast, $emit}

!16

Scope

Page 17: AngularJS - TechTalk 3/2/2014

Controller A

Controller B Controller C

$on(‘eventB’, …)

$on(‘eventA’, …)$on(‘eventA’, …)

$broadcast(‘eventA’, …)$emit(‘eventB’, …) $emit(‘eventC’, …)

$on(‘eventC’, …)

$broadcast(‘eventA’, …)

$emit(‘eventC’, …)$emit(‘eventB’, …)

!17

$rootScope.$on(‘eventC’, …)

Page 18: AngularJS - TechTalk 3/2/2014

❖ Scope is not the model!

❖ $scope.foo, where the foo is the model

❖ data-binding, <p>{{foo.bar}}</p>

❖ a portion of view is bind to a model

❖ when either one changes, they are both synchronized

!18

Model

Page 19: AngularJS - TechTalk 3/2/2014

View

!19

Page 20: AngularJS - TechTalk 3/2/2014

❖ presentation logic

❖ does not know anything about the controller, nor the controller about it

❖ everything goes through the Scope

❖ integrates with models, directives, filters

!20

View

Page 21: AngularJS - TechTalk 3/2/2014

❖ ng-repeat

❖ this would not work<div ng-repeat=“number in [1, 2, 3]”> <input type=“text” ng-model=“number” /></div> but this would work<div ng-repeat=“number in [{n: 1}, {n: 2}, {n: 3}]”> <input type=“text” ng-model="number.n"/></div>

❖ $index, $first, $middle, $last, $event, $parent

❖ ng-click, ng-show, ng-model, ng-change, ng-href …

!21

View

Page 22: AngularJS - TechTalk 3/2/2014

❖ orderBy, filter

❖ <div id=“{{post.id}}” ng-repeat=“post in posts| orderBy:order:descending| filter:filter”> </div>

❖ in Controller $scope.order = ‘date’ $scope.descending = true

❖ and filter would come from an text box

❖ ngClassEvent, ngClassOdd

!22

View

Page 23: AngularJS - TechTalk 3/2/2014

❖ compilation for templates and markup is done in two steps

!23

Step 1: compile

1) template examined for directives 2) AngularJS collects them and

produces a link function * no data has been inserted in the template

Step 2: link

1) scope into the link function of its directive 2) get back AngularJS element representing

the DOM fragment

View

var linker = $compile(template) var compiled = linker(scope)

$compile(template)(scope)

Page 24: AngularJS - TechTalk 3/2/2014

Controller

!24

Page 25: AngularJS - TechTalk 3/2/2014

❖ they are for the business logic

❖ they are not meant to interact with the DOM

❖ services can be injected to share common functionality with other controllers

!25

Controller

Page 26: AngularJS - TechTalk 3/2/2014

❖ A nice way to create modular applications

❖ it is magic (but not really…)

❖ Angular converts functions to strings .toString()

❖ runs string matching against them

❖ determines from the name of the parameter what you want to inject

!26

Dependency Injection

Page 27: AngularJS - TechTalk 3/2/2014

Directives

!27

Page 28: AngularJS - TechTalk 3/2/2014

❖ Create your own DSL

❖ A nice way to include logic in the views

❖ this is where DOM manipulation should happen!

❖ Can have an isolated scope

❖ Defines a linking function

❖ is passed a Scope object, an element, and the element’s attributes (optionally a controller inst.)

❖ where the logic goes

❖ Need a scope, use link. Don’t? Use compile.

!28

Directives

Page 29: AngularJS - TechTalk 3/2/2014

Directives

!29

compile()

HTML with directivesHTML with directivesHTML with directives

link (scope)

Scope object

<my-directive>

Compiled template with

data

examines finds returns

returns

Hiller, Christopher. “Developing an AngularJS Edge.”

Page 30: AngularJS - TechTalk 3/2/2014

app.directive(‘new-event’, function() { return { restrict: ‘E’, scope: { event: ‘=’, save: ‘=’, cancel: ‘=’, saveText: ‘@’, cancelText: ‘@’ }, replace: true, template: ‘<div ng-show="event">' + ‘<input type=“text” ng-model=“event.temp.title”/><br/>’ + ‘<input type=“text” ng-model=“event.temp.subtitle”></../>’ + ‘<button ng-click=“cancel(event)”>{{cancelText}}</button>’ + ‘<button ng-click=“save(event)”>{{saveText}}</button></div>’ }; });

!30

}}

linked to the parent scope

copied verbatim

Directives

Page 31: AngularJS - TechTalk 3/2/2014

<new-event event=“event” cancel=“cancel” save=“save” cancel-text=“Cancel” save-text=“Save”> </new-event>

!31

linked to the parent scope

copied verbatim

Directives

Page 32: AngularJS - TechTalk 3/2/2014

!32

app.directive(‘event-info', function() { return { restrict: ‘E’, replace: true, templateUrl: ‘views/eventInfo.html’ transclude: true, scope: { startDate: ‘=’, endDate: ‘=’ }, link: function(scope, element) { infoButton = element.children()[0].children[0].children[0] scope.open = false; angular.element(infoButton).bind(‘click’, function() { scope.$apply(‘open = !open’); }); }; }; });

Directives

Page 33: AngularJS - TechTalk 3/2/2014

!33

<div class="event-info"> <div class="event-info-content"> <div class="event-title" ng-transclude> <span class=“addtional-info-button”>More...</span> </div> <div class="additional-info>" ng-show="open"> <div class=“event-start">{{startDate}}</div> <div class="event-end">{{endDate}}</div> </div> </div> </div>

We could call it like: <event-info start-date=“event.event_start" end-date="event.event_end"> {{event.title.en}} </event-info>

Directives

Page 34: AngularJS - TechTalk 3/2/2014

❖ ‘=foo’ links directly to parent scope

❖ ‘@foo’ assigns an attribute to whatever the key is

❖ ‘&foo’ binds expression and executes it against the parent scope

❖ in directive definition: scope: {‘close’: ‘&onClose’}

❖ <my-directive on-close=“hide()”></my-directive>

❖ in directive’s template: ng-click=“close()”

❖ There are also ‘A’, ‘AE’, ‘C’, and ‘M’ restrict options

!34

Directives

Page 35: AngularJS - TechTalk 3/2/2014

❖ write reusable and generic directives

❖ the less reusable (involving scopes) the less maintainable they become

❖ write directives with isolated scopes!

❖ share functionality between directives using a controller

❖ long learning curve, but powerful!

!35

Directives

Page 36: AngularJS - TechTalk 3/2/2014

Service | Factory | Provider

!36

Page 37: AngularJS - TechTalk 3/2/2014

❖ the backbone of the an AngularJS app

❖ keep the controller from thinking too hard

❖ … and directives have only one function, make it readable and testable (inject services)

!37

Service | Factory | Provider

Page 38: AngularJS - TechTalk 3/2/2014

!38

Component Instantiated Needs a $get method

Explicitly returns something

Present during $config()

Service Yes No No No

Factory No No Yes No

Provider Yes Yes No Yes

Hiller, Christopher. “Developing an AngularJS Edge.”

Service | Factory | Provider

Page 39: AngularJS - TechTalk 3/2/2014

❖ it is a singleton, instantiated the first time is requested

❖ requires less memory and processing power than the others

!39

Service

Page 40: AngularJS - TechTalk 3/2/2014

!40

Events (Service)

EventsCtrl (Controller)

Promise Server

1) Calls getEvents()

2) Asks Server for a list of Events

3) Returns a Promise

Promises

Page 41: AngularJS - TechTalk 3/2/2014

!41

Events (Service)

EventsCtrl (Controller) Promise

Server

5) Promise resolved with events data

4) Returns a list of events

6) Takes action with data received from resolved promise

Promises

Page 42: AngularJS - TechTalk 3/2/2014

❖ it can return a function, object, or primitive

❖ useful for utils

!42

Factory

Page 43: AngularJS - TechTalk 3/2/2014

❖ can be configured during initialization

❖ $http is also a provider

!43

config() $httpProvider

run() $http

injects

injects

Provider

Page 44: AngularJS - TechTalk 3/2/2014

!44

DialogProvider

Plugin A

Plugin B

Dialog

Uses plugin B at runtime

Hiller, Christopher. “Developing an AngularJS Edge.”

Configure with Plugin B in Module.config()

Provider

Page 45: AngularJS - TechTalk 3/2/2014

Filters

!45

Page 46: AngularJS - TechTalk 3/2/2014

❖ execute logic against models only the view cares about

❖ app.filter(‘product’, function() { return function(a, b, c) { return a * b * c; }; });

❖ can be used like:<span>the product is {{a|product:b:c}}</span>

❖ executed often, so keep them simple

❖ they should not have side-effects

!46

Filters

Page 47: AngularJS - TechTalk 3/2/2014

❖ History

❖ Routing

❖ Compiler

❖ Injector

❖ Template

!47

More…

Page 48: AngularJS - TechTalk 3/2/2014

❖ Jasmine (behavior-driven testing)

❖ aware of asynchronous events

❖ take advantage of binding information

❖ excellent mock objects ($log)

!48

Testing (intro)

Page 49: AngularJS - TechTalk 3/2/2014

❖ http://ngmodules.org/, currently 440 modules (++)

❖ angular-ui, bootstrap, ui-router

❖ restangular

❖ angular-translate

❖ angular-cache

❖ …

!49

ng-modules

Page 50: AngularJS - TechTalk 3/2/2014

❖ http://builtwith.angularjs.org/

❖ http://www.google.com/doubleclick/Create, transact, and manage digital advertising

❖ http://demo.songpane.com/ Form song set lists (songs, lyrics, chords)

❖ http://www.zaptravel.com/Deals for experiences of interest

❖ http://hat.jit.su/Distributed scrum planning poker

❖ …

!50

built.with.angularjs

Page 51: AngularJS - TechTalk 3/2/2014

❖ Hiller, Christopher. “Developing an AngularJS Edge.”

❖ Mastering Web Application Development with AngularJS

❖ Ari Lerner “ng-book - The Complete Book on AngularJS”

!51

References

Page 52: AngularJS - TechTalk 3/2/2014
Page 53: AngularJS - TechTalk 3/2/2014

AAAAngularosum!