AngularJS - TechTalk 3/2/2014
-
Upload
spyros-ioakeimidis -
Category
Technology
-
view
7.878 -
download
0
Transcript of AngularJS - TechTalk 3/2/2014
TechTalk | 3 February 2014 Spyros Ioakeimidis
AngularJS
❖ Seemed a bit weird in the beginning
❖ All these new terms and concepts…
!2
!3
Factories
Providers
Services
Controllers
Views
ModelsFilte
rs
Directives
ModulesDependency Injection
Promises
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
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
!6
Modules
!7
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
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
MVC (or whatever…)
!10
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
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.”
Scope.models
!13
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
❖ $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
❖ $scope.$digest()
❖ $scope.$eval()
❖ $scope.{$on, $broadcast, $emit}
!16
Scope
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’, …)
❖ 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
View
!19
❖ 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
❖ 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
❖ 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
❖ 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)
Controller
!24
❖ 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
❖ 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
Directives
!27
❖ 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
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.”
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
<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
!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
!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
❖ ‘=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
❖ 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
Service | Factory | Provider
!36
❖ 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
!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
❖ it is a singleton, instantiated the first time is requested
❖ requires less memory and processing power than the others
!39
Service
!40
Events (Service)
EventsCtrl (Controller)
Promise Server
1) Calls getEvents()
2) Asks Server for a list of Events
3) Returns a Promise
Promises
!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
❖ it can return a function, object, or primitive
❖ useful for utils
!42
Factory
❖ can be configured during initialization
❖ $http is also a provider
!43
config() $httpProvider
run() $http
injects
injects
Provider
!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
Filters
!45
❖ 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
❖ History
❖ Routing
❖ Compiler
❖ Injector
❖ Template
!47
More…
❖ Jasmine (behavior-driven testing)
❖ aware of asynchronous events
❖ take advantage of binding information
❖ excellent mock objects ($log)
!48
Testing (intro)
❖ http://ngmodules.org/, currently 440 modules (++)
❖ angular-ui, bootstrap, ui-router
❖ restangular
❖ angular-translate
❖ angular-cache
❖ …
!49
ng-modules
❖ 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
❖ Hiller, Christopher. “Developing an AngularJS Edge.”
❖ Mastering Web Application Development with AngularJS
❖ Ari Lerner “ng-book - The Complete Book on AngularJS”
!51
References
AAAAngularosum!