IPT – Intellectual Products & Technologies SPA Development...
Transcript of IPT – Intellectual Products & Technologies SPA Development...
IPT – Intellectual Products & Technologies Trayan Iliev, http://www.iproduct.org/
AngularJS and TypeScript
SPA Development
Slide 1Sources: AngularJS [ https://docs.angularjs.org ], AngularJS Hub [ http://www.angularjshub.com/ ]
Licensed under the Creative Commons Attribution-ShareAlike 3.0 License
AngularJS
Trayan Iliev
IPT – Intellectual Products & Technologiese-mail: [email protected]
web: http://www.iproduct.org
Oracle®, Java™ and JavaScript™ are trademarks or registered trademarks of Oracle and/or its affiliates.Microsoft .NET, Visual Studio and Visual Studio Code are trademarks of Microsoft Corporation.
Other names may be trademarks of their respective owners.
IPT – Intellectual Products & Technologies Trayan Iliev, http://www.iproduct.org/
AngularJS and TypeScript
SPA Development
Slide 2Sources: AngularJS [ https://docs.angularjs.org ], AngularJS Hub [ http://www.angularjshub.com/ ]
Licensed under the Creative Commons Attribution-ShareAlike 3.0 License
Agenda
1. MVW patterns: MVC, MVP, MVVM2. Single Page Applications (SPA)3. JavaScript frameworks4. Introduction to AngularJS5. AngularJS Main Concepts6. Data binding – uni- and bi-directional7. Using controllers, services and directives8. AngularJS scopes, hierachy & scopes watching strategies9. AngularJS dependency Injection10.Integration with browser event loop11.Directives and scopes
IPT – Intellectual Products & Technologies Trayan Iliev, http://www.iproduct.org/
AngularJS and TypeScript
SPA Development
Slide 3Sources: AngularJS [ https://docs.angularjs.org ], AngularJS Hub [ http://www.angularjshub.com/ ]
Licensed under the Creative Commons Attribution-ShareAlike 3.0 License
MVC Comes in Different Flavors
What is the difference between following patterns:
Model-View-Controller (MVC) Model-View-ViewModel (MVVM) Model-View-Presenter (MVP)
http://csl.ensm-douai.fr/noury/uploads/20/ModelViewController.mp3
IPT – Intellectual Products & Technologies Trayan Iliev, http://www.iproduct.org/
AngularJS and TypeScript
SPA Development
Slide 4Sources: AngularJS [ https://docs.angularjs.org ], AngularJS Hub [ http://www.angularjshub.com/ ]
Licensed under the Creative Commons Attribution-ShareAlike 3.0 License
MVC Comes in Different Flavors - 2
MVC
MVVM
MVP
Sources:https://en.wikipedia.org/wiki/Model_View_ViewModel#/media/File:MVVMPattern.png, https://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93presenter#/media/File:Model_View_Presenter_GUI_Design_Pattern.pngLicense: CC BY-SA 3.0, Authors:Ugaya40, Daniel.Cardenas
IPT – Intellectual Products & Technologies Trayan Iliev, http://www.iproduct.org/
AngularJS and TypeScript
SPA Development
Slide 5Sources: AngularJS [ https://docs.angularjs.org ], AngularJS Hub [ http://www.angularjshub.com/ ]
Licensed under the Creative Commons Attribution-ShareAlike 3.0 License
Web MVC Interactions Sequence Diagram
IPT – Intellectual Products & Technologies Trayan Iliev, http://www.iproduct.org/
AngularJS and TypeScript
SPA Development
Slide 6Sources: AngularJS [ https://docs.angularjs.org ], AngularJS Hub [ http://www.angularjshub.com/ ]
Licensed under the Creative Commons Attribution-ShareAlike 3.0 License
Sinagle Page Apps (SPA) in 3 steps
1) Setting up a build system – npm, webpack, gulp are common choices, babel, typescript, JSX, CSS preprocessors (SASS, SCSS, LESS), jasmine, karma, protractor, Yeoman/ Slush, live servers
2) Designing front-end architecture components – views & layouts + view models (presentation data models) + presentation logic (event handling, messaging) + routing paths (essential for SPA)
Better to use component model to boost productivity and maintainability.
3) End-to-end application design – front-end: wireframes → views,data entities & data streams → service API and models design,sitemap → router config
Trayan Iliev IPT – Intellectual Products & Technologies Ltd.
Разработка на уеб приложения с AJAX библиотеки
16/02/2015 Slide 7Copyright © 2003-2016 IPT – Intellectual Products & Technologies Ltd. All rights reserved.
JavaScript MV* Frameworks [Google Trends]
IPT – Intellectual Products & Technologies Trayan Iliev, http://www.iproduct.org/
AngularJS and TypeScript
SPA Development
Slide 8Sources: AngularJS [ https://docs.angularjs.org ], AngularJS Hub [ http://www.angularjshub.com/ ]
Licensed under the Creative Commons Attribution-ShareAlike 3.0 License
Introduction to AngularJS
Structural framework for dynamic web apps in the browser
Directives – extensible HTML templates syntax for components:
Data binding, as in {{}}.DOM control structures for repeating, showing and hiding DOM fragments.Support for forms and form validation.Attaching new behavior to DOM elements, such as DOM event handling.Grouping of HTML into reusable components.
Data binding and dependency injection – no boilerplate code
IPT – Intellectual Products & Technologies Trayan Iliev, http://www.iproduct.org/
AngularJS and TypeScript
SPA Development
Slide 9Sources: AngularJS [ https://docs.angularjs.org ], AngularJS Hub [ http://www.angularjshub.com/ ]
Licensed under the Creative Commons Attribution-ShareAlike 3.0 License
Complete Client-Side Solution
Everything you need to build a CRUD app in a cohesive set:
Data-binding and templating directivesForm validationRouting and deep-linkingReusable componentsDependency injection
Testability – unit-testing, end-to-end testing, mocks and test harnesses
Seed application with directory layout and test scripts as a starting point.
IPT – Intellectual Products & Technologies Trayan Iliev, http://www.iproduct.org/
AngularJS and TypeScript
SPA Development
Slide 10Sources: AngularJS [ https://docs.angularjs.org ], AngularJS Hub [ http://www.angularjshub.com/ ]
Licensed under the Creative Commons Attribution-ShareAlike 3.0 License
AngularJS Advantages
Decouples DOM manipulation from app logic - improved code testability
Framework guides developers through the entire journey of building an app – from designing the UI, through writing the business logic, to testing.
Makes common tasks trivial and difficult tasks possible
Mainatainable Single Page Applications (SPAs)
DI: separation of concerns + minimal ceremony (boilerplate)
Crossplatform – all major browsers supported + Android & iOS (Ionic mobile app framework, Material Design - MD)
IPT – Intellectual Products & Technologies Trayan Iliev, http://www.iproduct.org/
AngularJS and TypeScript
SPA Development
Slide 11Sources: AngularJS [ https://docs.angularjs.org ], AngularJS Hub [ http://www.angularjshub.com/ ]
Licensed under the Creative Commons Attribution-ShareAlike 3.0 License
AngularJS Main Concepts
Template – HTML with additional markup
Directives – extend HTML with custom attributes and elements
Model – the data shown to the user in the view and with which the user interacts
Scope – context where the model is stored so that controllers, directives and expressions can access it
Expressions – access variables and functions from the scope
Compiler – parses the template and instantiates directives and expressions
Filter – formats the value of an expression to display to the user
IPT – Intellectual Products & Technologies Trayan Iliev, http://www.iproduct.org/
AngularJS and TypeScript
SPA Development
Slide 12Sources: AngularJS [ https://docs.angularjs.org ], AngularJS Hub [ http://www.angularjshub.com/ ]
Licensed under the Creative Commons Attribution-ShareAlike 3.0 License
AngularJS Main Concepts (2)
View – what the user sees (the DOM)
Data Binding – sync data between the model and the view
Controller – the business logic behind views
Dependency Injection – Creates and wires objects and functions
Injector – dependency injection container
Module – a container for the different parts of an app including controllers, services, filters, directives which configures the Injector
Service – reusable business logic independent of views
IPT – Intellectual Products & Technologies Trayan Iliev, http://www.iproduct.org/
AngularJS and TypeScript
SPA Development
Slide 13Sources: AngularJS [ https://docs.angularjs.org ], AngularJS Hub [ http://www.angularjshub.com/ ]
Licensed under the Creative Commons Attribution-ShareAlike 3.0 License
Introduction to AngularJS
<div ng-app ng-init="qty=1;cost=2"> <b>Invoice:</b> <div> Quantity: <input type="number" min="0" ng-model="qty"> </div> <div> Costs: <input type="number" min="0" ng-model="cost"> </div> <div> <b>Total:</b> {{qty * cost | currency}} </div></div>
IPT – Intellectual Products & Technologies Trayan Iliev, http://www.iproduct.org/
AngularJS and TypeScript
SPA Development
Slide 14Sources: AngularJS [ https://docs.angularjs.org ], AngularJS Hub [ http://www.angularjshub.com/ ]
Licensed under the Creative Commons Attribution-ShareAlike 3.0 License
Binding Scope (View Model) to View
Template
View – loaded, transformed and rendered DOM template by compiler.
In Angular, the only place where an application should access the DOM is within directives → custom directives
Directive
Expression
Trayan Iliev IPT – Intellectual Products & Technologies Ltd.
Разработка на уеб приложения с AJAX библиотеки
16/02/2015 Slide 15Copyright © 2003-2016 IPT – Intellectual Products & Technologies Ltd. All rights reserved.
Data Binding
Source: AngularJS Developer Guide: https://docs.angularjs.org/guide/databindingLicense: CC BY-3.0
IPT – Intellectual Products & Technologies Trayan Iliev, http://www.iproduct.org/
AngularJS and TypeScript
SPA Development
Slide 16Sources: AngularJS [ https://docs.angularjs.org ], AngularJS Hub [ http://www.angularjshub.com/ ]
Licensed under the Creative Commons Attribution-ShareAlike 3.0 License
AngularJS Controllers
Controller = constructor function augmenting scope (view model)
ng-controller – directive that attaches controller to DOM and creates new child scope - injectable parameter to the controller's constructor function as $scope
Controller as syntax preferred (see AngularJS Style Guide – https://github.com/johnpapa/angular-styleguide/tree/master/a1) assigns the controller instance to a property on the new scope
Controller's purpose:
Set up the initial state of the $scope objectAdd behavior to the $scope object
IPT – Intellectual Products & Technologies Trayan Iliev, http://www.iproduct.org/
AngularJS and TypeScript
SPA Development
Slide 17Sources: AngularJS [ https://docs.angularjs.org ], AngularJS Hub [ http://www.angularjshub.com/ ]
Licensed under the Creative Commons Attribution-ShareAlike 3.0 License
AngularJS Controllers DO NOTs:
✗ Manipulate DOM – controllers should contain only logic, not DOM manipulation – otherwise testability suffers. Angular has databinding for most cases and directives to encapsulate manual DOM manipulation.
✗ Format input – use angular form controls instead
✗ Filter output – use angular filters instead
✗ Share code or state across controllers – use angular services instead.
✗ Manage the life-cycle of other components (for example, to create service instances).
IPT – Intellectual Products & Technologies Trayan Iliev, http://www.iproduct.org/
AngularJS and TypeScript
SPA Development
Slide 18Sources: AngularJS [ https://docs.angularjs.org ], AngularJS Hub [ http://www.angularjshub.com/ ]
Licensed under the Creative Commons Attribution-ShareAlike 3.0 License
Using Controllers<div ng-app="invoice3" ng-controller="InvoiceController as invoice"> <b>Invoice:</b> <div>Quantity: <input type="number" min="0" ng-model="invoice.qty" required></div> <div>Costs: <input type="number" min="0" ng-model="invoice.cost" required> <select ng-model="invoice.inCurr"> <option ng-repeat="c in invoice.currencies">{{c}}</option> </select> </div> <div> <b>Total:</b> <span ng-repeat="c in invoice.currencies"> {{invoice.total(c) | currency:c}} </span> <button class="btn" ng-click="invoice.pay()">Pay</button> </div></div>
IPT – Intellectual Products & Technologies Trayan Iliev, http://www.iproduct.org/
AngularJS and TypeScript
SPA Development
Slide 19Sources: AngularJS [ https://docs.angularjs.org ], AngularJS Hub [ http://www.angularjshub.com/ ]
Licensed under the Creative Commons Attribution-ShareAlike 3.0 License
InvoiceController (1) - Imports
'use strict';import * as angular from 'angular';import './finance2';import {CurrencyConverter} from './finance2';
IPT – Intellectual Products & Technologies Trayan Iliev, http://www.iproduct.org/
AngularJS and TypeScript
SPA Development
Slide 20Sources: AngularJS [ https://docs.angularjs.org ], AngularJS Hub [ http://www.angularjshub.com/ ]
Licensed under the Creative Commons Attribution-ShareAlike 3.0 License
InvoiceController (2)angular.module('invoice2', ['finance2']) .controller('InvoiceController', ['currencyConverter', function (currencyConverter: CurrencyConverter): void { this.qty = 1; this.cost = 2; this.inCurr = 'EUR'; this.currencies = currencyConverter.currencies;
this.total = function total(outCurr: string) { return currencyConverter.convert(this.qty * this.cost, this.inCurr, outCurr); }; this.pay = function pay(): void { window.alert('Thanks!'); }; }]);
IPT – Intellectual Products & Technologies Trayan Iliev, http://www.iproduct.org/
AngularJS and TypeScript
SPA Development
Slide 21Sources: AngularJS [ https://docs.angularjs.org ], AngularJS Hub [ http://www.angularjshub.com/ ]
Licensed under the Creative Commons Attribution-ShareAlike 3.0 License
Model – View – Controller
View Model
Controller = View Specific Logic
Controller Instance
View / TemplateController
Declaration
IPT – Intellectual Products & Technologies Trayan Iliev, http://www.iproduct.org/
AngularJS and TypeScript
SPA Development
Slide 22Sources: AngularJS [ https://docs.angularjs.org ], AngularJS Hub [ http://www.angularjshub.com/ ]
Licensed under the Creative Commons Attribution-ShareAlike 3.0 License
CurrencyConverter Service Interface
'use strict';import * as angular from 'angular';
export interface CurrencyConverter { currencies: Array<string>; convert: (amount: number, inCurr: string, outCurr: string) => number;}
IPT – Intellectual Products & Technologies Trayan Iliev, http://www.iproduct.org/
AngularJS and TypeScript
SPA Development
Slide 23Sources: AngularJS [ https://docs.angularjs.org ], AngularJS Hub [ http://www.angularjshub.com/ ]
Licensed under the Creative Commons Attribution-ShareAlike 3.0 License
CurrencyConverter Service Implementationangular.module('finance2', []) .factory('currencyConverter', function() { this.currencies = ['USD', 'EUR', 'CNY']; this.usdToForeignRates = { CNY: 6.09, EUR: 0.74, USD: 1 }; let convert = (amount: number, inCurr: string, outCurr: string)=> { return amount * this.usdToForeignRates[outCurr] / this.usdToForeignRates[inCurr]; }; return { convert: convert, currencies: this.currencies };});
IPT – Intellectual Products & Technologies Trayan Iliev, http://www.iproduct.org/
AngularJS and TypeScript
SPA Development
Slide 24Sources: AngularJS [ https://docs.angularjs.org ], AngularJS Hub [ http://www.angularjshub.com/ ]
Licensed under the Creative Commons Attribution-ShareAlike 3.0 License
Service Factory & Dependency Injection
Main Module
Controller
View Template
Dependencies (Modules)
Service = Business Logic
DI
DI Factory (Provider) Function
IPT – Intellectual Products & Technologies Trayan Iliev, http://www.iproduct.org/
AngularJS and TypeScript
SPA Development
Slide 25Sources: AngularJS [ https://docs.angularjs.org ], AngularJS Hub [ http://www.angularjshub.com/ ]
Licensed under the Creative Commons Attribution-ShareAlike 3.0 License
Real World Services: Yahoo Finance API (1)
import * as angular from 'angular';
export interface CurrencyConverter { currencies: Array<string>; convert: CurrencyConverterFunction;}
interface CurrencyConverterFunction { (amount: number, inCurr: string, outCurr: string): number;}
interface CurrencyRates { [cirrencyName: string]: number;}
IPT – Intellectual Products & Technologies Trayan Iliev, http://www.iproduct.org/
AngularJS and TypeScript
SPA Development
Slide 26Sources: AngularJS [ https://docs.angularjs.org ], AngularJS Hub [ http://www.angularjshub.com/ ]
Licensed under the Creative Commons Attribution-ShareAlike 3.0 License
Real World Services: Yahoo Finance API (2)
interface YahooFinanceForeignRate { id: string; Rate: string;}
interface YahooFinanceForeignRatesResult { query: { results: { rate: YahooFinanceForeignRate[]; } };}
IPT – Intellectual Products & Technologies Trayan Iliev, http://www.iproduct.org/
AngularJS and TypeScript
SPA Development
Slide 27Sources: AngularJS [ https://docs.angularjs.org ], AngularJS Hub [ http://www.angularjshub.com/ ]
Licensed under the Creative Commons Attribution-ShareAlike 3.0 License
Real World Services: Yahoo Finance API (3)angular.module('finance3', []) .factory('currencyConverter', ['$http', function ($http: ng.IHttpService) { const YAHOO_FINANCE_URL_PATTERN = '//query.yahooapis.com/v1/public/yql?q=select * from ' + 'yahoo.finance.xchange where pair in ("PAIRS")&format=json&' +'env=store://datatables.org/alltableswithkeys&callback=JSON_CALLBACK'; const currencies: string[] = ['USD', 'EUR', 'CNY']; let usdToForeignRates: CurrencyRates = {}; let convert: CurrencyConverterFunction = function (amount, inCurr, outCurr) { return amount * usdToForeignRates[outCurr] / usdToForeignRates[inCurr]; }; let refresh = function () { const url = YAHOO_FINANCE_URL_PATTERN. replace('PAIRS', 'USD' + currencies.join('","USD')); ...
Service Dependency Injection (DI)
IPT – Intellectual Products & Technologies Trayan Iliev, http://www.iproduct.org/
AngularJS and TypeScript
SPA Development
Slide 28Sources: AngularJS [ https://docs.angularjs.org ], AngularJS Hub [ http://www.angularjshub.com/ ]
Licensed under the Creative Commons Attribution-ShareAlike 3.0 License
Real World Services: Yahoo Finance API (4) ... return $http.jsonp(url).then( (response: ng.IHttpPromiseCallbackArg<{}>) => { let newUsdToForeignRates: CurrencyRates = {}; angular.forEach( (<YahooFinanceForeignRatesResult>response.data).query.results.rate, (rate: YahooFinanceForeignRate) => { let currency: string = rate.id.substring(3, 6); newUsdToForeignRates[currency] = parseFloat(rate.Rate); } ); usdToForeignRates = newUsdToForeignRates; });};refresh();return { convert: convert, currencies: currencies};}]);
IPT – Intellectual Products & Technologies Trayan Iliev, http://www.iproduct.org/
AngularJS and TypeScript
SPA Development
Slide 29Sources: AngularJS [ https://docs.angularjs.org ], AngularJS Hub [ http://www.angularjshub.com/ ]
Licensed under the Creative Commons Attribution-ShareAlike 3.0 License
AngularJS Scopes (1)
IPT – Intellectual Products & Technologies Trayan Iliev, http://www.iproduct.org/
AngularJS and TypeScript
SPA Development
Slide 30Sources: AngularJS [ https://docs.angularjs.org ], AngularJS Hub [ http://www.angularjshub.com/ ]
Licensed under the Creative Commons Attribution-ShareAlike 3.0 License
AngularJS Sopes (2)Scope = object that refers to the application model, context for expressions.
Scopes are arranged in hierarchical structure which mimic the DOM structure of the application.
Child scope – (prototypically) inherits properties from its parent
Isolate scope – does not inherit properties from its parent
Able to inspect scope for selected element in the browser as: angular.element($0).scope() from browser console
Root scope is automatically created and associated with element using ng-app directive → $rootScope using DI
Scopes can watch expressions and propagate events
IPT – Intellectual Products & Technologies Trayan Iliev, http://www.iproduct.org/
AngularJS and TypeScript
SPA Development
Slide 31Sources: AngularJS [ https://docs.angularjs.org ], AngularJS Hub [ http://www.angularjshub.com/ ]
Licensed under the Creative Commons Attribution-ShareAlike 3.0 License
AngularJS Bootstraping
IPT – Intellectual Products & Technologies Trayan Iliev, http://www.iproduct.org/
AngularJS and TypeScript
SPA Development
Slide 32Sources: AngularJS [ https://docs.angularjs.org ], AngularJS Hub [ http://www.angularjshub.com/ ]
Licensed under the Creative Commons Attribution-ShareAlike 3.0 License
AngularJS Scope API (1)
$new(isolate, parent) – creates a new child scope. The parent scope will propagate the $digest() event. The scope can be removed from the scope hierarchy using $destroy()$destroy() - called when desired for the scope and its child scopes to be permanently detached from parent and thus stop participating in model change detection and listener notification$eval([expression], [locals]) – executes the expression and returns the result$watch(watchExpression, listener, [objectEquality]) – registers listener callback executed whenever watchExpression changes$digest() - processes all watchers of the current scope and its children. Usually not called directly but using $apply([exp])
Trayan Iliev IPT – Intellectual Products & Technologies Ltd.
Разработка на уеб приложения с AJAX библиотеки
16/02/2015 Slide 33Copyright © 2003-2016 IPT – Intellectual Products & Technologies Ltd. All rights reserved.
Pseudo-Code of $apply()
function $apply(expr) {
try {
return $eval(expr);
} catch (e) {
$exceptionHandler(e);
} finally {
$root.$digest();
}
IPT – Intellectual Products & Technologies Trayan Iliev, http://www.iproduct.org/
AngularJS and TypeScript
SPA Development
Slide 34Sources: AngularJS [ https://docs.angularjs.org ], AngularJS Hub [ http://www.angularjshub.com/ ]
Licensed under the Creative Commons Attribution-ShareAlike 3.0 License
Scopes Watching Strategies
IPT – Intellectual Products & Technologies Trayan Iliev, http://www.iproduct.org/
AngularJS and TypeScript
SPA Development
Slide 35Sources: AngularJS [ https://docs.angularjs.org ], AngularJS Hub [ http://www.angularjshub.com/ ]
Licensed under the Creative Commons Attribution-ShareAlike 3.0 License
Integration with Browser Event Loop
IPT – Intellectual Products & Technologies Trayan Iliev, http://www.iproduct.org/
AngularJS and TypeScript
SPA Development
Slide 36Sources: AngularJS [ https://docs.angularjs.org ], AngularJS Hub [ http://www.angularjshub.com/ ]
Licensed under the Creative Commons Attribution-ShareAlike 3.0 License
AngularJS Scope API (2)
$on(name, listener) – listens on events of a given type
$emit(name, args) - dispatches an event name upwards through the scope hierarchy notifying the registered listeners
$broadcast(name, args) – dispatches an event name downwards to all child scopes (and their children) notifying the registered listeners
angular.module('eventExample', []).controller('EventController', ['$scope', function($scope) { $scope.count = 0; $scope.$on('MyEvent', function() { $scope.count++; });}]);
IPT – Intellectual Products & Technologies Trayan Iliev, http://www.iproduct.org/
AngularJS and TypeScript
SPA Development
Slide 37Sources: AngularJS [ https://docs.angularjs.org ], AngularJS Hub [ http://www.angularjshub.com/ ]
Licensed under the Creative Commons Attribution-ShareAlike 3.0 License
Scope Events[https://docs.angularjs.org/guide/scope#scope-events-propagation]
<div ng-controller="EventController"> Root scope <tt>MyEvent</tt> count: {{count}} <ul> <li ng-repeat="i in [1]" ng-controller="EventController"> <button ng-click="$emit('MyEvent')">$emit('MyEvent')</button> <button ng-click="$broadcast('MyEvent')"> $broadcast('MyEvent')</button> <br> Middle scope <tt>MyEvent</tt> count: {{count}} <ul> <li ng-repeat="item in [1, 2]" ng-controller="EventController"> Leaf scope <tt>MyEvent</tt> count: {{count}} </li> </ul> </li> </ul></div>
IPT – Intellectual Products & Technologies Trayan Iliev, http://www.iproduct.org/
AngularJS and TypeScript
SPA Development
Slide 38Sources: AngularJS [ https://docs.angularjs.org ], AngularJS Hub [ http://www.angularjshub.com/ ]
Licensed under the Creative Commons Attribution-ShareAlike 3.0 License
Event Listener and Event Object
The event listener function format is: function(event, args...)
The event object passed into listener has following attributes:
targetScope - {Scope}: the scope on which the event was $emit-ed or $broadcast-ed
currentScope – {Scope}: scope currently handling event
name - {string}: name of the event
stopPropagation - {function}: cancels further event propagation (available only for events that were $emit-ed)
preventDefault - {function}: sets defaultPrevented to true
defaultPrevented - {boolean}: true if preventDefault called
IPT – Intellectual Products & Technologies Trayan Iliev, http://www.iproduct.org/
AngularJS and TypeScript
SPA Development
Slide 39Sources: AngularJS [ https://docs.angularjs.org ], AngularJS Hub [ http://www.angularjshub.com/ ]
Licensed under the Creative Commons Attribution-ShareAlike 3.0 License
AngularJS Scopes Hierachy
Trayan Iliev IPT – Intellectual Products & Technologies Ltd.
Разработка на уеб приложения с AJAX библиотеки
16/02/2015 Slide 40Copyright © 2003-2016 IPT – Intellectual Products & Technologies Ltd. All rights reserved.
Controllers and Scope Inheritance (1)
var myApp = angular.module('scopeInheritance', [])
.controller('MainController', ['$scope', function($scope) { $scope.timeOfDay = 'morning'; $scope.name = 'Nikki';}])
.controller('ChildController', ['$scope', function($scope) { $scope.name = 'Mattie';}])
.controller('GrandChildController', ['$scope', function($scope) { $scope.timeOfDay = 'evening'; $scope.name = 'Gingerbread Baby';}]);
IPT – Intellectual Products & Technologies Trayan Iliev, http://www.iproduct.org/
AngularJS and TypeScript
SPA Development
Slide 41Sources: AngularJS [ https://docs.angularjs.org ], AngularJS Hub [ http://www.angularjshub.com/ ]
Licensed under the Creative Commons Attribution-ShareAlike 3.0 License
Controllers and Scope Inheritance (2)[https://docs.angularjs.org/guide/controller#scope-inheritance-example]
<div ng-controller="MainController"> <p>Good {{timeOfDay}}, {{name}}!</p> <div ng-controller="ChildController"> <p>Good {{timeOfDay}}, {{name}}!</p> <div ng-controller="GrandChildController"> <p>Good {{timeOfDay}}, {{name}}!</p> </div> </div></div>
IPT – Intellectual Products & Technologies Trayan Iliev, http://www.iproduct.org/
AngularJS and TypeScript
SPA Development
Slide 42Sources: AngularJS [ https://docs.angularjs.org ], AngularJS Hub [ http://www.angularjshub.com/ ]
Licensed under the Creative Commons Attribution-ShareAlike 3.0 License
AngularJS Modules
Controller = container for app parts – controllers, services, filters, directives, etc.
Declarative approach instead of main method – advantages:
The declarative process is easier to understandYou can package code as reusable modules.The modules can be loaded in any order (or even in parallel) because modules delay executionUnit tests only have to load relevant modules, which keeps them fastEnd-to-end tests can use modules to override configuration
IPT – Intellectual Products & Technologies Trayan Iliev, http://www.iproduct.org/
AngularJS and TypeScript
SPA Development
Slide 43Sources: AngularJS [ https://docs.angularjs.org ], AngularJS Hub [ http://www.angularjshub.com/ ]
Licensed under the Creative Commons Attribution-ShareAlike 3.0 License
Module Setup & Configuaration [https://github.com/johnpapa/angular-styleguide/tree/master/a1]
Recommended project setup:
A module for each featureA module for each reusable component (especially directives and filters)An application level module which depends on the above modules and contains any initialization code
Declarative approach instead of main method – advantages:
Configuration blocks - executed during provider registrations and configuration phase → providers and constants only Run blocks - executed after injector created, app kickstart → instances and constants only (prevent further config)
IPT – Intellectual Products & Technologies Trayan Iliev, http://www.iproduct.org/
AngularJS and TypeScript
SPA Development
Slide 44Sources: AngularJS [ https://docs.angularjs.org ], AngularJS Hub [ http://www.angularjshub.com/ ]
Licensed under the Creative Commons Attribution-ShareAlike 3.0 License
Module Configuaration & Loading
angular.module('myModule', []).config(function(injectables) { // provider-injector // This is an example of config block. // You can have as many of these as you want. // You can only inject Providers (not instances) // into config blocks.}).run(function(injectables) { // instance-injector // This is an example of a run block. // You can have as many of these as you want. // You can only inject instances (not Providers) // into run blocks});
IPT – Intellectual Products & Technologies Trayan Iliev, http://www.iproduct.org/
AngularJS and TypeScript
SPA Development
Slide 45Sources: AngularJS [ https://docs.angularjs.org ], AngularJS Hub [ http://www.angularjshub.com/ ]
Licensed under the Creative Commons Attribution-ShareAlike 3.0 License
Module Configuaration Exampleangular.module('myModule', []). value('a', 123). factory('a', function() { return 123; }). directive('directiveName', ...). filter('filterName', ...);
// is same as
angular.module('myModule', []). config(function($provide, $compileProvider, $filterProvider) { $provide.value('a', 123); $provide.factory('a', function() { return 123; }); $compileProvider.directive('directiveName', ...); $filterProvider.register('filterName', ...); });
IPT – Intellectual Products & Technologies Trayan Iliev, http://www.iproduct.org/
AngularJS and TypeScript
SPA Development
Slide 46Sources: AngularJS [ https://docs.angularjs.org ], AngularJS Hub [ http://www.angularjshub.com/ ]
Licensed under the Creative Commons Attribution-ShareAlike 3.0 License
AngularJS Module API (1)
$provide service – registering components with the $injector. Functions exposed also on angular.Module:
provider(name, provider) – registers a service provider with the $injectorconstant(name, obj) – registers a value/object that can be accessed by providers and services, can not be decorated using decoratorvalue(name, obj) – registers a value/object that can only be accessed by services, not providers, and can be decorated using decorator
IPT – Intellectual Products & Technologies Trayan Iliev, http://www.iproduct.org/
AngularJS and TypeScript
SPA Development
Slide 47Sources: AngularJS [ https://docs.angularjs.org ], AngularJS Hub [ http://www.angularjshub.com/ ]
Licensed under the Creative Commons Attribution-ShareAlike 3.0 License
AngularJS Module API (2)
$provide service – registering components with the $injector. Functions exposed also on angular.Module:
factory(name, fn) – registers a service factory function that will be wrapped in a service provider object, whose $get property will contain the given factory functionservice(name, Fn) – registers a constructor function that will be wrapped in a service provider object, whose $get property will instantiate a new object using the given constructor functiondecorator(name, decorFn) – registers a decorator function ($delegate injected as argument), able to modify or replace the implementation of another service/ directive/ filter/ value
IPT – Intellectual Products & Technologies Trayan Iliev, http://www.iproduct.org/
AngularJS and TypeScript
SPA Development
Slide 48Sources: AngularJS [ https://docs.angularjs.org ], AngularJS Hub [ http://www.angularjshub.com/ ]
Licensed under the Creative Commons Attribution-ShareAlike 3.0 License
Decorator Example: $log Service angular.module('myApp', []).config([ '$provide', function($provide) {
$provide.decorator('$log', [ '$delegate', function $logDecorator($delegate) {
var originalWarn = $delegate.warn; $delegate.warn = function decoratedWarn(msg) { msg = 'Decorated Warn: ' + msg; originalWarn.apply($delegate, arguments); };
return $delegate; } ]);
IPT – Intellectual Products & Technologies Trayan Iliev, http://www.iproduct.org/
AngularJS and TypeScript
SPA Development
Slide 49Sources: AngularJS [ https://docs.angularjs.org ], AngularJS Hub [ http://www.angularjshub.com/ ]
Licensed under the Creative Commons Attribution-ShareAlike 3.0 License
AngularJS Module API (3)
$filterProvider.register(name, factory) – filters are functions that transform input to an output. To be able to use DI a filter definition consists of a factory function which is annotated with dependencies, and is responsible for creating a filter function:
function MyModule($provide, $filterProvider) { // create a service to demonstrate injection (not always needed) $provide.value('greet', function(name){ return 'Hello '+name+'!'; }); // register a filter factory which uses the greet service by DI $filterProvider.register('greet', function(greet){ return function(text) { // filters need to be forgiving so check input validity return text && greet(text) || text; }; });}
IPT – Intellectual Products & Technologies Trayan Iliev, http://www.iproduct.org/
AngularJS and TypeScript
SPA Development
Slide 50Sources: AngularJS [ https://docs.angularjs.org ], AngularJS Hub [ http://www.angularjshub.com/ ]
Licensed under the Creative Commons Attribution-ShareAlike 3.0 License
AngularJS Module API (4)
$compileProvider service – registering directives and components with the $injector. Exposed on angular.Module as:
directive(name, directiveFactory) – registers a new directive with the compilercomponent(name, options) – registers a component definition with the compiler. Shorthand for registering a special type of directive, which represents a self-contained UI component in your application. Such components are always isolated (i.e. scope: {}) and are always restricted to elements (i.e. restrict: 'E').See more at: https://docs.angularjs.org/guide/directive, andhttps://docs.angularjs.org/guide/component
IPT – Intellectual Products & Technologies Trayan Iliev, http://www.iproduct.org/
AngularJS and TypeScript
SPA Development
Slide 51Sources: AngularJS [ https://docs.angularjs.org ], AngularJS Hub [ http://www.angularjshub.com/ ]
Licensed under the Creative Commons Attribution-ShareAlike 3.0 License
Custom Directive Exampleconst ENTER_KEY = 13;angular.module('keyEvents',[]).directive('onEnter', ['$log', onEnter]);function onEnter($log: ng.ILogService): ng.IDirective { return { link: ($scope: ng.IScope, element: JQuery, attributes: any):void => { element.bind('keydown', (event: JQueryEventObject) => { if (event.keyCode === ENTER_KEY) { $log.info('ENTER key pressed'); $scope.$apply(attributes.onEnter); } }); $scope.$on('$destroy', () => { element.unbind('keydown'); }); } };}
IPT – Intellectual Products & Technologies Trayan Iliev, http://www.iproduct.org/
AngularJS and TypeScript
SPA Development
Slide 52Sources: AngularJS [ https://docs.angularjs.org ], AngularJS Hub [ http://www.angularjshub.com/ ]
Licensed under the Creative Commons Attribution-ShareAlike 3.0 License
Main Directives (1)
ng-app – bootstraps the application:
load the module associated with the directivecreate the application injector compile the DOM treating the ngApp element as root
ng-strict-di – strict dependency injection (minification safe)
ng-controller – defines new controller (using constructor function) for the element and its descendants
<div ng-app="ngAppStrictDemo" ng-strict-di> <div ng-controller="Controller1"> I can add: {{a}} + {{b}} = {{ a+b }} </div></div>
IPT – Intellectual Products & Technologies Trayan Iliev, http://www.iproduct.org/
AngularJS and TypeScript
SPA Development
Slide 53Sources: AngularJS [ https://docs.angularjs.org ], AngularJS Hub [ http://www.angularjshub.com/ ]
Licensed under the Creative Commons Attribution-ShareAlike 3.0 License
How Dependency Injection Works
IPT – Intellectual Products & Technologies Trayan Iliev, http://www.iproduct.org/
AngularJS and TypeScript
SPA Development
Slide 54Sources: AngularJS [ https://docs.angularjs.org ], AngularJS Hub [ http://www.angularjshub.com/ ]
Licensed under the Creative Commons Attribution-ShareAlike 3.0 License
AngularJS Dependency Injection
IPT – Intellectual Products & Technologies Trayan Iliev, http://www.iproduct.org/
AngularJS and TypeScript
SPA Development
Slide 55Sources: AngularJS [ https://docs.angularjs.org ], AngularJS Hub [ http://www.angularjshub.com/ ]
Licensed under the Creative Commons Attribution-ShareAlike 3.0 License
Dependency Injection Stylesangular.module('ngAppStrictDemo', [])// Fails to instantiate, due to automatic function annotation.controller('BadController', function($scope) { $scope.a = 1; $scope.b = 2;})// Instantiated, due to explicit annotations (array, $inject property).controller('GoodController1', ['$scope', function($scope) { $scope.a = 1; $scope.b = 2;}]).controller('GoodController2', GoodController2);function GoodController2($scope) { $scope.name = "World";}GoodController2.$inject = ['$scope'];
IPT – Intellectual Products & Technologies Trayan Iliev, http://www.iproduct.org/
AngularJS and TypeScript
SPA Development
Slide 56Sources: AngularJS [ https://docs.angularjs.org ], AngularJS Hub [ http://www.angularjshub.com/ ]
Licensed under the Creative Commons Attribution-ShareAlike 3.0 License
Programmatic Dependency Injection
Creating injector instance (usually done automatically during bootstrap) and getting a service instance from instance cash:
let injector = angular.injector(['ng', 'finance3'], true);let currencyConverter = <CurrencyConverter>injector.get('currencyConverter');
Better idea – to inject the $injector service itself, instead of creating second injector:
angular.module('invoice4', ['finance3', 'keyEvents']) .controller('InvoiceController',['$injector', function ($injector: ng.auto.IInjectorService): void { ... let currencyConverter = <CurrencyConverter>$injector.get('currencyConverter');
...}]);// OR injector.instantiate(MyController); in case of Constructor
IPT – Intellectual Products & Technologies Trayan Iliev, http://www.iproduct.org/
AngularJS and TypeScript
SPA Development
Slide 57Sources: AngularJS [ https://docs.angularjs.org ], AngularJS Hub [ http://www.angularjshub.com/ ]
Licensed under the Creative Commons Attribution-ShareAlike 3.0 License
Main Directives (2)
ng-show, ng-hide – show and hide the element conditionally
ng-if – allows to conditionally insert or remove an element
ng-switch, ng-switch-when, ng-switch-default – work together to show conditionally elements in the DOM based on a selector expression
ng-include – includes an external resource in an HTML template – e.g. a fragment of a HTML template depending on a specific condition.
ng-repeat – clones compiled DOM template and creates a new scope for each element in a collection
IPT – Intellectual Products & Technologies Trayan Iliev, http://www.iproduct.org/
AngularJS and TypeScript
SPA Development
Slide 58Sources: AngularJS [ https://docs.angularjs.org ], AngularJS Hub [ http://www.angularjshub.com/ ]
Licensed under the Creative Commons Attribution-ShareAlike 3.0 License
ng-repeat Scopes
IPT – Intellectual Products & Technologies Trayan Iliev, http://www.iproduct.org/
AngularJS and TypeScript
SPA Development
Slide 59Sources: AngularJS [ https://docs.angularjs.org ], AngularJS Hub [ http://www.angularjshub.com/ ]
Licensed under the Creative Commons Attribution-ShareAlike 3.0 License
Compiling and Linking Directives[https://docs.angularjs.org/api/ng/service/$compile#example]
Compiler – AngularJS service which traverses the DOM looking for direxctives.
Compilation process happens in two phases:➔ Compile – traverse the DOM and collect all of the directives.
The result is a linking function.➔ Link – combine the directives with a scope and produce a live
view.Changes in scope model are reflected in the view, and user interactions with view are reflected in the scope model
Some directives such as ng-repeat clone DOM elements once for each item in a collection. Having a compile and link phase improves performance – cloned template is compiled once
IPT – Intellectual Products & Technologies Trayan Iliev, http://www.iproduct.org/
AngularJS and TypeScript
SPA Development
Slide 60Sources: AngularJS [ https://docs.angularjs.org ], AngularJS Hub [ http://www.angularjshub.com/ ]
Licensed under the Creative Commons Attribution-ShareAlike 3.0 License
AngularJS Directive Normalization[https://docs.angularjs.org/guide/compiler]
A directive is a behavior (function) which is triggered when specific HTML constructs are encountered in compilation: element names, attributes, class names, comments
<span ng-bind="exp"></span> <span ng:bind="exp"></span> <br/> <span ng_bind="exp"></span> <br/> <span data-ng-bind="exp"></span> <br/> <span x-ng-bind="exp"></span> <span class="ng-bind: exp;"></span> <ng-bind></ng-bind> <!-- directive: ng-bind exp --> --compilation--> ngBind directive
IPT – Intellectual Products & Technologies Trayan Iliev, http://www.iproduct.org/
AngularJS and TypeScript
SPA Development
Slide 61Sources: AngularJS [ https://docs.angularjs.org ], AngularJS Hub [ http://www.angularjshub.com/ ]
Licensed under the Creative Commons Attribution-ShareAlike 3.0 License
Directive Controllers Life-cycle Hooks (1)[https://docs.angularjs.org/api/ng/service/$compile#life-cycle-hooks]
$onInit() - called on each controller after all the controllers on an element have been constructed and had their bindings initialized (and before the pre & post linking functions)
$onChanges(changesObj) - called whenever one-way (<) or interpolation (@) bindings are updated. The changesObj is a hash whose keys are the names of the bound properties that have changed, and the values are an object of the form { currentValue, previousValue, isFirstChange() }
$doCheck() - called on each turn of the digest cycle. Provides opportunity to detect and act on changes. Implementing this has no effect on when $onChanges is called. This hook could be useful if you wish to perform a deep equality check.
IPT – Intellectual Products & Technologies Trayan Iliev, http://www.iproduct.org/
AngularJS and TypeScript
SPA Development
Slide 62Sources: AngularJS [ https://docs.angularjs.org ], AngularJS Hub [ http://www.angularjshub.com/ ]
Licensed under the Creative Commons Attribution-ShareAlike 3.0 License
Directive Controllers Life-cycle Hooks (2)[https://docs.angularjs.org/api/ng/service/$compile#life-cycle-hooks]
$onDestroy() - called on a controller when its containing scope is destroyed. Use this hook for releasing external resources, watches and event handlers. Parent components will have their $onDestroy() hook called before child components.
$postLink() - Called after this controller's element and its children have been linked. Similar to the post-link function this hook can be used to set up DOM event handlers and do direct DOM manipulation. Note that child elements that contain templateUrl directives will not have been compiled and linked since they are waiting for their template to load asynchronously and their own compilation and linking has been suspended until that occurs
IPT – Intellectual Products & Technologies Trayan Iliev, http://www.iproduct.org/
AngularJS and TypeScript
SPA Development
Slide 63Sources: AngularJS [ https://docs.angularjs.org ], AngularJS Hub [ http://www.angularjshub.com/ ]
Licensed under the Creative Commons Attribution-ShareAlike 3.0 License
Thanks for Your Attention!
Questions?