SlideShare a Scribd company logo
Workingwith
Microsoft WebCamp 2014
May 20, 2014
2Aboutme
/56
André Vala
SharePoint Solutions Architect
Office & SharePoint Solutions Team Leader
andre.vala@create.pt
@atomicvee
http://blogit.create.pt/blogs/andrevala
http://www.linkedin.com/in/andrevala
3Agenda
 What is AngularJS?
 Main Concepts
 Tools
 BestPractices
 Wrappingup
/56
WhatisAngularJS?
“Angular is what HTML would have
been had it been designed for
applications.”
Miško Hevery
6WhatisAngularJS?
 SinglePageApplication(SPA)JavaScriptFramework
 Implementsclient-sideMVW pattern
 No directDOM manipulation, lesscode
 Wellorganizedand highly modular
 Focusedon testing
 Supports all majordesktopand mobilebrowsers
/56
Read More: https://plus.google.com/+AngularJS/posts/aZNVhj355G2
7History
 Createdby MiškoHevery
 Opensourcesince2009
 Supportedby Google
 Large and fast-growingcommunity
WHATISANGULARJS? /56
8SinglePageApplications
 Webapplicationscomposedof a singlepage
 Views(HTML Fragments)aredynamicallyloaded into the page
 Betteruserexperience(no reloads!)
 Calls to the serveraredone asynchronouslybehind the scenes
 Requireartificialhandling of browserhistory, navigation and
bookmarks
WHATISANGULARJS? /56
9Model-View-Whatever
 Somecallit MVC, othersMVVM...
 In the end, the namedoes not
matter. It handles separationof
concernsefectivelyseparating
presentationlogicfrombusiness
logicand presentationstate.
 Whatevermeans “whatever
worksfor you”.
WHATISANGULARJS? /56
Read More: https://plus.google.com/+AngularJS/posts/aZNVhj355G2
Model View
Whatever
10Trendingtopic
WHATISANGULARJS? /56
Source: Google Trends
11Learningcurve
WHATISANGULARJS? /56
MainConcepts
13Mainconcepts
 Templates
 Directives
 Expressions
 Data binding
 Scope
/56
 Controllers
 Modules
 Filters
 Services
 Routing
HelloWorld
DEMOMAINCONCEPTS
15Helloworldapplication
MAINCONCEPTS /56
<!doctype html>
<html ng-app>
<head>
<title>Demo 01 - Page 03</title>
<script src="libs/angular.min.js"></script>
</head>
<body>
<p>Name:<input id="textInput" type="text" ng-model="PersonName" /></p>
<p>Hello <span id="nameSpan">{{PersonName}}</span>!</p>
</body>
</html>
Directive
Directive
Expression
Template
16Templates
 HTML with additional markup
 Directives
 Expressions
 Filters
 Formcontrols
MAINCONCEPTS /56
Read More: https://docs.angularjs.org/guide/templates
17Directives
Markerson DOM elementsthat extendHTML vocabulary
 Attachbehaviourtothe DOMelement
 TransformtheDOM elementanditschildren
Directivescanmatch:
Elements <my-dir></my-dir>
Attributes <span my-dir="exp"></span>
Comments <!-- directive: my-dir exp -->
Classes <span class="my-dir: exp;"></span>
MAINCONCEPTS /56
Read More: https://docs.angularjs.org/guide/directive
18Namingformats
AngularJS HTML compilersupports multiplenamingformats
ng-bind Recommendedformat.
data-ng-bind Recommendedformattosupport HTMLvalidators.
ng_bind Legacypurposes. Avoidusingit.
ng:bind Legacypurposes. Avoidusing it.
x-ng-bind Legacypurposes. Avoidusing it.
MAINCONCEPTS/DIRECTIVES /56
Read More: https://docs.angularjs.org/guide/directive
19Built-indirectives
ngApp ngBind ngBindHtml ngBindTemplate ngBlur ngChange
ngChecked ngClass ngClassEven ngClassOdd ngClick ngCloak
ngController ngCopy ngCsp ngCut ngDblClick ngDisabled
ngFocus ngForm ngHide ngHref ngIf ngInclude ngInit
ngKeydown ngKeypress ngKeyup ngList ngModel ngModelOptions
ngMousedown ngMouseenter ngMouseleave ngMousemove
ngMouseover ngNonBindable ngOpen ngPaste ngPluralize
ngReadonly ngRepeat ngSelected ngShow ngSrc ngSrcset
ngStyle ngSubmit ngTransclude ngValue ngView
MAINCONCEPTS/DIRECTIVES /56
Read More: https://docs.angularjs.org/guide/directive
20Expressions
JavaScript-likecodesnippetsplacedinsidebindingssuchas
{{ expression }}
ValidAngularexpressions:
 {{ 1 + 2 }}
 {{ a + b }}
 {{ user.name }}
 {{ items[index] }}
Additionalnotesaboutexpressions:
 Controlflowstatementsarenotsupported(conditionals,loopsorexceptions)
 Youcanusefiltersinsideexpressionstoformatdata
MAINCONCEPTS /56
Read More: https://docs.angularjs.org/guide/expression
Expressions
DEMOMAINCONCEPTS
22Databinding
Automatic synchronizationof data betweenthe Modeland the View.
MAINCONCEPTS /56
Read More: https://docs.angularjs.org/guide/databinding
View
Template Model
One-time
merge
One-WayDataBinding
View
Template
Model
Continuous updates
Model is Single-Source-of-Truth
Compile
Changes to Model
updates View
Changes to View
updates Model
Two-WayDataBinding
Two-waydatabinding
DEMOMAINCONCEPTS
24Scope
 Objectthat refersto the applicationModel
 Valuesstored in variablesin the Scopebelong to the Model
 The glue betweenthe Controllerand the View
 Scopesarehierarchicaland followthe
DOM structureof the application
 EveryAngular applicationhas a root
scope($rootScope)mapped to the
elementlinked to ngApp directive
MAINCONCEPTS /56
Read More: https://docs.angularjs.org/guide/scope
25Controllers
 JavaScriptconstructorfunctions used to augmentthe Scope
 Newchild scopeis createdand
injectedas a constructor
parameter($scope)
MAINCONCEPTS /56
Read More: https://docs.angularjs.org/guide/controller
26Howtousecontrollers
Creatinga controllerinthe globalnamespace
function MyController($scope) {
...
}
Attachinga controllerto the DOM
<div ng-controller="MyController">
MAINCONCEPTS/CONTROLLERS /56
Read More: https://docs.angularjs.org/guide/controller
27Whentousecontrollers
 Usecontrollersto:
 Setup theinitialstateofthe$scope object
 Add behaviourtothe$scope object
 Do not use controllersto:
 ManipulateDOM(usedatabindinganddirectivesinstead)
 Formatinput (useformcontrolsinstead)
 Filteroutput (usefiltersinstead)
 Sharecodeorstateacrosscontrollers(useservicesinstead)
MAINCONCEPTS/CONTROLLERS /56
Read More: https://docs.angularjs.org/guide/controller
Usingcontrollers
DEMOMAINCONCEPTS
29Module
 Reusablecontainerfor differentfeaturesof anapp.
 Candependon othermodules.
Creatinga module
angular.module('myApp', []);
angular.module('myApp', ['myOtherModule']);
Referencinganapp’smainmodule
<html ng-app="myApp">
MAINCONCEPTS /56
Read More: https://docs.angularjs.org/guide/module
Usingmodules
DEMOMAINCONCEPTS
31Filters
 A filterformatsthevalueof anexpressionfor display to the user
 Can be used in view templates,controllers,servicesand directives
 You can createyour ownfilters (in a module)
 Built-in filters:
MAINCONCEPTS /56
Read More: https://docs.angularjs.org/guide/filter
Currency
Date
Filter
Json
LimitTo
Lowercase
Number
OrderBy
Uppercase
32Usingfiltersinviewtemplates
Singlefiltersyntax
{{ expression | filter }}
Example:{{ 12 | currency }} returns $12.00
Chainedfilterssyntax
{{ expression | filter1 | filter2 | ... }}
Filterwitharguments
{{ expression | filter:argument1:argument2... }}
Example:{{ 12 | number:2 }} returns 12.00
MAINCONCEPTS/FILTERS /56
Read More: https://docs.angularjs.org/guide/filter
33Usingfiltersincontrollers,servicesanddirectives
angular.module('FilterInControllerModule', []).
controller('FilterController', ['filterFilter', function(filterFilter) {
this.array = [
{name: 'Tobias'},
{name: 'Jeff'},
{name: 'Brian'},
{name: 'Igor'},
{name: 'James'},
{name: 'Brad'}
];
this.filteredArray = filterFilter(this.array, 'a');
}]);
MAINCONCEPTS/FILTERS /56
Read More: https://docs.angularjs.org/guide/filter
Inject filter in controller using
<filter name>Filter syntax
Receive filter function
as a parameter
Call filter with value to format
and additional parameters
34Creatingfilters
angular.module('MyFilterModule', []).
filter('myfilter', function() {
return function(input) {
...
return output;
};
});
MAINCONCEPTS/FILTERS /56
Read More: https://docs.angularjs.org/guide/filter
User the filter provider to
create a new filter in the
module
Name the filter
Return the filter function. The first
argument is the input value.
Additional arguments can be used.
Usingfilters
DEMOMAINCONCEPTS
36Services
 Reusablebusiness logiccomponentes,independentof views,wired
togetherusing dependencyinjection(DI).
 Singletonsgeneratedby a servicefactory.
 Angular only instantiatesa serviceif thereis a dependencyfor it.
 Built-in servicesstart with $.
Examples:$log, $http, $filter,$exceptionHandler
MAINCONCEPTS /56
Read More: https://docs.angularjs.org/guide/services
37Usingaservice
var countryApp = angular.module('countryApp', []);
countryApp.controller('CountryCtrl', ['$scope', '$http', function (scope, http) {
http.get(‘countries.json').success(function(data) {
scope.countries = data;
});
}]);
MAINCONCEPTS/SERVICES /56
Inject $http service using DI
Receive service object
as a parameter
Call method on service
Read More: https://docs.angularjs.org/guide/services
38Creatingaservice
var myModule = angular.module('myModule', []);
myModule.factory('serviceId', function() {
var shinyNewServiceInstance;
//factory function body that constructs shinyNewServiceInstance
return shinyNewServiceInstance;
});
MAINCONCEPTS/SERVICES /56
Return a service instance
Register a new factory function for the service
Read More: https://docs.angularjs.org/guide/services
39Recipes
var myApp = angular.module('myApp',[]);
myApp.provider('MyFactory', function() {...});
myApp.factory('MyFactory', function() {...});
myApp.service('MyFactory', function() {...});
myApp.constant('MyConstant', 'My Constant Value');
myApp.value('MyValue', 35);
MAINCONCEPTS/SERVICES /56
Usingservices
DEMOMAINCONCEPTS
41Multipleviews
 Most applicationsarecomposedof morethan one view
 In Single PageApplicationsall viewsare renderedin the same page
(LayoutTemplate)which containsall the commonpage elements
 Eachview(PartialTemplate)is placedin its own file and dynamically
loadedinto the LayoutTemplate page
MAINCONCEPTS /56
42Multipleviews
MAINCONCEPTS /56
index.html
header.html
a1.html b2.html
a2.html
b1.html
b3.html
a3.html
Layout Template
Partial Template
Partial Template
Partial Template
Partial Template
43Routing
 Routing is providedby the ngRoute module(separatedistribution)
 Routesare declaredvia the $routeProvider fromthe $route service
 Supports deeplinking(history,bookmarksand browserback/forward
buttons)
 Partialviewsarerenderedby the ngView directive
MAINCONCEPTS /56
44Routingconfiguration
var myApp = angular.module('myApp',['ngRoute']);
myApp.config(['$routeProvider',
function($routeProvider) {
$routeProvider.
when('/phones', {
templateUrl: 'partials/phone-list.html',
controller: 'PhoneListCtrl‘
}).
when('/phones/:phoneId', {
templateUrl: 'partials/phone-detail.html',
controller: 'PhoneDetailCtrl'
}).
otherwise({
redirectTo: '/phones'
});
}]);
MAINCONCEPTS/ROUTING /56
Route
Dependency on
ngRoute module
Default Route
Route with variable URL. PhoneId value
will be placed in $routeParams object
Routing
DEMOMAINCONCEPTS
Bestpractices
47BestPractices
 In Views/Templates
 Usedirectivesforabstractingcommonmarkups,extensions
 Donotusecomplexexpressionsinbindings.Movethemtocontrollers.
 Optimizeuseofbindings.Lessbindings=fasterapplication.
 In Controllers
 Keepthemlight.Useservicestooffloadfunctionality.
 NoDOMmanipulations!Usedirectivesforthat.
/56
48BestPractices
 In Directives
 Preferusingdirectivesaselementsorattributesoverclassesandcomments
 Donotng-prefixforyourdirectives
 Createisolatescopestoavoidacidentaloverridesofproperties
 Createmodulesto group controllers,services,directivesand filters
/56
Tools
50Tools
 IDE: Visual Studio, NetBeans,WebStorm
 Utils: JSFiddle, BatarangPlugin for Chrome
 Static Code Analysis:JSHint
 Unit Testing: Karma
/56
Wrappingup
52Wrappingup
 AngularJS is a modular JavaScriptSPA framework
 Has a lot of great featuresbut a steeplearningcurve
 Greatfor CRUD applicationsbut not suitable for everytype of
application
 Worksvery wellwith some JavaScriptlibraries(such as jQuery)but
not so wellwith others
 Increasesdeveloperproductivity in small/medium applicationsbut
can be quite heavyfor complexapplications
/56
53Nexttime...
 Custom directives
 Formcontrolsand validation
 Unit testing
 End-to-endtesting
 Animations
WRAPPINGUP /56
54Resources
Officialdocumentation
 Projecthomepage:https://angularjs.org/
 DeveloperGuide:https://docs.angularjs.org/guide
 Tutorial:https://docs.angularjs.org/tutorial
 APIReference:https://docs.angularjs.org/api
 BuiltwithAngular:https://builtwith.angularjs.org
Trainingvideosandtutorialsfordevelopers
 Egghead:https://egghead.io/technologies/angularjs
Additionalstuff
 Angularmodules:http://ngmodules.org/
WRAPPINGUP /56
ThankYou!
Downloadslidedeck:http://1drv.ms/1h1YOlS
Downloaddemos:http://1drv.ms/1h1YJyP
Working with AngularJS

More Related Content

PDF
The Role of Python in SPAs (Single-Page Applications)
PDF
How to Webpack your Django!
PDF
Jetpack, with new features in 2021 GDG Georgetown IO Extended
PPT
Angular 8
PDF
An Introduction to Django Web Framework
PDF
Building an app with Google's new suites
PDF
Introduction to Vaadin
PDF
Zukunftssichere Anwendungen mit AngularJS 1.x entwickeln (GDG DevFest Karlsru...
The Role of Python in SPAs (Single-Page Applications)
How to Webpack your Django!
Jetpack, with new features in 2021 GDG Georgetown IO Extended
Angular 8
An Introduction to Django Web Framework
Building an app with Google's new suites
Introduction to Vaadin
Zukunftssichere Anwendungen mit AngularJS 1.x entwickeln (GDG DevFest Karlsru...

What's hot (20)

PPTX
Angular js
PDF
Techlunch - Dependency Injection with Vaadin
PDF
A gently introduction to AngularJS
PDF
Sharper Better Faster Dagger ‡ - Droidcon SF
PPTX
Angular 2 어디까지 왔을까
PDF
AngularJS Project Setup step-by- step guide - RapidValue Solutions
PDF
Building impressive layout systems with vaadin
PDF
Vaadin Components @ Angular U
PDF
Android DevConference - Android Clean Architecture
DOCX
Different way to share data between controllers in angular js
PDF
Angular Mini Hackathon Code Talks 2019
PDF
Introduction to React for Frontend Developers
PPTX
React django
PPTX
Modern android development
PDF
Building maintainable app
PDF
Vaadin DevDay 2017 - DI your UI
PPTX
Introduction to Google Guice
PDF
Vaadin Components
PDF
Modular Test-driven SPAs with Spring and AngularJS
PDF
Exploring CameraX from JetPack
Angular js
Techlunch - Dependency Injection with Vaadin
A gently introduction to AngularJS
Sharper Better Faster Dagger ‡ - Droidcon SF
Angular 2 어디까지 왔을까
AngularJS Project Setup step-by- step guide - RapidValue Solutions
Building impressive layout systems with vaadin
Vaadin Components @ Angular U
Android DevConference - Android Clean Architecture
Different way to share data between controllers in angular js
Angular Mini Hackathon Code Talks 2019
Introduction to React for Frontend Developers
React django
Modern android development
Building maintainable app
Vaadin DevDay 2017 - DI your UI
Introduction to Google Guice
Vaadin Components
Modular Test-driven SPAs with Spring and AngularJS
Exploring CameraX from JetPack
Ad

Similar to Working with AngularJS (20)

PDF
AngularJS: Overview & Key Features
PPT
Coffee@DBG - Exploring Angular JS
PPTX
Intro to AngularJs
PDF
AngularJS Deep Dives (NYC GDG Apr 2013)
PDF
Introduction to AngularJS
PDF
PDF
AngularJS Workshop
PPTX
Learning AngularJS - Complete coverage of AngularJS features and concepts
PPTX
Angular workshop - Full Development Guide
PPTX
Angular js
PPTX
Intoduction to Angularjs
PDF
Introduction to AngularJS
PPTX
Dive into Angular, part 1: Introduction
PDF
CraftCamp for Students - Introduction to AngularJS
PPSX
PPTX
Understanding angular js
PPTX
AngularJS = Browser applications on steroids
PPTX
AngularJS.part1
PPTX
Angular Presentation
AngularJS: Overview & Key Features
Coffee@DBG - Exploring Angular JS
Intro to AngularJs
AngularJS Deep Dives (NYC GDG Apr 2013)
Introduction to AngularJS
AngularJS Workshop
Learning AngularJS - Complete coverage of AngularJS features and concepts
Angular workshop - Full Development Guide
Angular js
Intoduction to Angularjs
Introduction to AngularJS
Dive into Angular, part 1: Introduction
CraftCamp for Students - Introduction to AngularJS
Understanding angular js
AngularJS = Browser applications on steroids
AngularJS.part1
Angular Presentation
Ad

More from André Vala (20)

PPTX
RGPD - Testemunho do Mundo Real
PPTX
Office Dev Day 2018 - Extending Microsoft Teams
PPTX
From Event Receivers to SharePoint Webhooks (SPS Lisbon 2017)
PPTX
From Event Receivers to SharePoint Webhooks
PPTX
Planning the Death Star with Microsoft Planner
PPTX
From Event Receivers to SharePoint Webhooks
PPTX
Microsoft Planner Deep Dive
PPTX
SharePoint - Presente e Futuro
PPTX
Office 365 Groups Deep Dive
PPTX
Soluções com Office Graph
PPTX
Host-Named Site Collections in SharePoint 2013
PPTX
User License Enforcement em SharePoint 2013
PPTX
How To Use Host-Named Site Collections
PPTX
Novidades na pesquisa no SharePoint 2013
PPTX
Building Public Web Sites in SharePoint 2010
PPTX
SharePoint + Azure = Better Together
PPTX
Federated Authentication in SharePoint 2010
PPTX
Using BCS to integrate Azure Services with SharePoint 2010
PPTX
LINQ to SharePoint
PPTX
Solução de Negócio baseadas em Office 2010 e SharePoint 2010
RGPD - Testemunho do Mundo Real
Office Dev Day 2018 - Extending Microsoft Teams
From Event Receivers to SharePoint Webhooks (SPS Lisbon 2017)
From Event Receivers to SharePoint Webhooks
Planning the Death Star with Microsoft Planner
From Event Receivers to SharePoint Webhooks
Microsoft Planner Deep Dive
SharePoint - Presente e Futuro
Office 365 Groups Deep Dive
Soluções com Office Graph
Host-Named Site Collections in SharePoint 2013
User License Enforcement em SharePoint 2013
How To Use Host-Named Site Collections
Novidades na pesquisa no SharePoint 2013
Building Public Web Sites in SharePoint 2010
SharePoint + Azure = Better Together
Federated Authentication in SharePoint 2010
Using BCS to integrate Azure Services with SharePoint 2010
LINQ to SharePoint
Solução de Negócio baseadas em Office 2010 e SharePoint 2010

Recently uploaded (20)

PDF
Modernizing your data center with Dell and AMD
PPTX
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
PPTX
Comunidade Salesforce São Paulo - Desmistificando o Omnistudio (Vlocity)
PDF
Spectral efficient network and resource selection model in 5G networks
PPTX
Cloud computing and distributed systems.
PDF
CIFDAQ's Market Wrap: Ethereum Leads, Bitcoin Lags, Institutions Shift
PDF
GamePlan Trading System Review: Professional Trader's Honest Take
PPTX
Big Data Technologies - Introduction.pptx
PPTX
Understanding_Digital_Forensics_Presentation.pptx
PDF
NewMind AI Weekly Chronicles - August'25 Week I
PDF
Chapter 2 Digital Image Fundamentals.pdf
PDF
Transforming Manufacturing operations through Intelligent Integrations
PDF
madgavkar20181017ppt McKinsey Presentation.pdf
PDF
solutions_manual_-_materials___processing_in_manufacturing__demargo_.pdf
PPTX
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PDF
HCSP-Presales-Campus Network Planning and Design V1.0 Training Material-Witho...
PDF
KodekX | Application Modernization Development
PPT
Teaching material agriculture food technology
Modernizing your data center with Dell and AMD
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
Comunidade Salesforce São Paulo - Desmistificando o Omnistudio (Vlocity)
Spectral efficient network and resource selection model in 5G networks
Cloud computing and distributed systems.
CIFDAQ's Market Wrap: Ethereum Leads, Bitcoin Lags, Institutions Shift
GamePlan Trading System Review: Professional Trader's Honest Take
Big Data Technologies - Introduction.pptx
Understanding_Digital_Forensics_Presentation.pptx
NewMind AI Weekly Chronicles - August'25 Week I
Chapter 2 Digital Image Fundamentals.pdf
Transforming Manufacturing operations through Intelligent Integrations
madgavkar20181017ppt McKinsey Presentation.pdf
solutions_manual_-_materials___processing_in_manufacturing__demargo_.pdf
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
Reach Out and Touch Someone: Haptics and Empathic Computing
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
HCSP-Presales-Campus Network Planning and Design V1.0 Training Material-Witho...
KodekX | Application Modernization Development
Teaching material agriculture food technology

Working with AngularJS

  • 2. 2Aboutme /56 André Vala SharePoint Solutions Architect Office & SharePoint Solutions Team Leader [email protected] @atomicvee http://blogit.create.pt/blogs/andrevala http://www.linkedin.com/in/andrevala
  • 3. 3Agenda  What is AngularJS?  Main Concepts  Tools  BestPractices  Wrappingup /56
  • 5. “Angular is what HTML would have been had it been designed for applications.” Miško Hevery
  • 6. 6WhatisAngularJS?  SinglePageApplication(SPA)JavaScriptFramework  Implementsclient-sideMVW pattern  No directDOM manipulation, lesscode  Wellorganizedand highly modular  Focusedon testing  Supports all majordesktopand mobilebrowsers /56 Read More: https://plus.google.com/+AngularJS/posts/aZNVhj355G2
  • 7. 7History  Createdby MiškoHevery  Opensourcesince2009  Supportedby Google  Large and fast-growingcommunity WHATISANGULARJS? /56
  • 8. 8SinglePageApplications  Webapplicationscomposedof a singlepage  Views(HTML Fragments)aredynamicallyloaded into the page  Betteruserexperience(no reloads!)  Calls to the serveraredone asynchronouslybehind the scenes  Requireartificialhandling of browserhistory, navigation and bookmarks WHATISANGULARJS? /56
  • 9. 9Model-View-Whatever  Somecallit MVC, othersMVVM...  In the end, the namedoes not matter. It handles separationof concernsefectivelyseparating presentationlogicfrombusiness logicand presentationstate.  Whatevermeans “whatever worksfor you”. WHATISANGULARJS? /56 Read More: https://plus.google.com/+AngularJS/posts/aZNVhj355G2 Model View Whatever
  • 13. 13Mainconcepts  Templates  Directives  Expressions  Data binding  Scope /56  Controllers  Modules  Filters  Services  Routing
  • 15. 15Helloworldapplication MAINCONCEPTS /56 <!doctype html> <html ng-app> <head> <title>Demo 01 - Page 03</title> <script src="libs/angular.min.js"></script> </head> <body> <p>Name:<input id="textInput" type="text" ng-model="PersonName" /></p> <p>Hello <span id="nameSpan">{{PersonName}}</span>!</p> </body> </html> Directive Directive Expression Template
  • 16. 16Templates  HTML with additional markup  Directives  Expressions  Filters  Formcontrols MAINCONCEPTS /56 Read More: https://docs.angularjs.org/guide/templates
  • 17. 17Directives Markerson DOM elementsthat extendHTML vocabulary  Attachbehaviourtothe DOMelement  TransformtheDOM elementanditschildren Directivescanmatch: Elements <my-dir></my-dir> Attributes <span my-dir="exp"></span> Comments <!-- directive: my-dir exp --> Classes <span class="my-dir: exp;"></span> MAINCONCEPTS /56 Read More: https://docs.angularjs.org/guide/directive
  • 18. 18Namingformats AngularJS HTML compilersupports multiplenamingformats ng-bind Recommendedformat. data-ng-bind Recommendedformattosupport HTMLvalidators. ng_bind Legacypurposes. Avoidusingit. ng:bind Legacypurposes. Avoidusing it. x-ng-bind Legacypurposes. Avoidusing it. MAINCONCEPTS/DIRECTIVES /56 Read More: https://docs.angularjs.org/guide/directive
  • 19. 19Built-indirectives ngApp ngBind ngBindHtml ngBindTemplate ngBlur ngChange ngChecked ngClass ngClassEven ngClassOdd ngClick ngCloak ngController ngCopy ngCsp ngCut ngDblClick ngDisabled ngFocus ngForm ngHide ngHref ngIf ngInclude ngInit ngKeydown ngKeypress ngKeyup ngList ngModel ngModelOptions ngMousedown ngMouseenter ngMouseleave ngMousemove ngMouseover ngNonBindable ngOpen ngPaste ngPluralize ngReadonly ngRepeat ngSelected ngShow ngSrc ngSrcset ngStyle ngSubmit ngTransclude ngValue ngView MAINCONCEPTS/DIRECTIVES /56 Read More: https://docs.angularjs.org/guide/directive
  • 20. 20Expressions JavaScript-likecodesnippetsplacedinsidebindingssuchas {{ expression }} ValidAngularexpressions:  {{ 1 + 2 }}  {{ a + b }}  {{ user.name }}  {{ items[index] }} Additionalnotesaboutexpressions:  Controlflowstatementsarenotsupported(conditionals,loopsorexceptions)  Youcanusefiltersinsideexpressionstoformatdata MAINCONCEPTS /56 Read More: https://docs.angularjs.org/guide/expression
  • 22. 22Databinding Automatic synchronizationof data betweenthe Modeland the View. MAINCONCEPTS /56 Read More: https://docs.angularjs.org/guide/databinding View Template Model One-time merge One-WayDataBinding View Template Model Continuous updates Model is Single-Source-of-Truth Compile Changes to Model updates View Changes to View updates Model Two-WayDataBinding
  • 24. 24Scope  Objectthat refersto the applicationModel  Valuesstored in variablesin the Scopebelong to the Model  The glue betweenthe Controllerand the View  Scopesarehierarchicaland followthe DOM structureof the application  EveryAngular applicationhas a root scope($rootScope)mapped to the elementlinked to ngApp directive MAINCONCEPTS /56 Read More: https://docs.angularjs.org/guide/scope
  • 25. 25Controllers  JavaScriptconstructorfunctions used to augmentthe Scope  Newchild scopeis createdand injectedas a constructor parameter($scope) MAINCONCEPTS /56 Read More: https://docs.angularjs.org/guide/controller
  • 26. 26Howtousecontrollers Creatinga controllerinthe globalnamespace function MyController($scope) { ... } Attachinga controllerto the DOM <div ng-controller="MyController"> MAINCONCEPTS/CONTROLLERS /56 Read More: https://docs.angularjs.org/guide/controller
  • 27. 27Whentousecontrollers  Usecontrollersto:  Setup theinitialstateofthe$scope object  Add behaviourtothe$scope object  Do not use controllersto:  ManipulateDOM(usedatabindinganddirectivesinstead)  Formatinput (useformcontrolsinstead)  Filteroutput (usefiltersinstead)  Sharecodeorstateacrosscontrollers(useservicesinstead) MAINCONCEPTS/CONTROLLERS /56 Read More: https://docs.angularjs.org/guide/controller
  • 29. 29Module  Reusablecontainerfor differentfeaturesof anapp.  Candependon othermodules. Creatinga module angular.module('myApp', []); angular.module('myApp', ['myOtherModule']); Referencinganapp’smainmodule <html ng-app="myApp"> MAINCONCEPTS /56 Read More: https://docs.angularjs.org/guide/module
  • 31. 31Filters  A filterformatsthevalueof anexpressionfor display to the user  Can be used in view templates,controllers,servicesand directives  You can createyour ownfilters (in a module)  Built-in filters: MAINCONCEPTS /56 Read More: https://docs.angularjs.org/guide/filter Currency Date Filter Json LimitTo Lowercase Number OrderBy Uppercase
  • 32. 32Usingfiltersinviewtemplates Singlefiltersyntax {{ expression | filter }} Example:{{ 12 | currency }} returns $12.00 Chainedfilterssyntax {{ expression | filter1 | filter2 | ... }} Filterwitharguments {{ expression | filter:argument1:argument2... }} Example:{{ 12 | number:2 }} returns 12.00 MAINCONCEPTS/FILTERS /56 Read More: https://docs.angularjs.org/guide/filter
  • 33. 33Usingfiltersincontrollers,servicesanddirectives angular.module('FilterInControllerModule', []). controller('FilterController', ['filterFilter', function(filterFilter) { this.array = [ {name: 'Tobias'}, {name: 'Jeff'}, {name: 'Brian'}, {name: 'Igor'}, {name: 'James'}, {name: 'Brad'} ]; this.filteredArray = filterFilter(this.array, 'a'); }]); MAINCONCEPTS/FILTERS /56 Read More: https://docs.angularjs.org/guide/filter Inject filter in controller using <filter name>Filter syntax Receive filter function as a parameter Call filter with value to format and additional parameters
  • 34. 34Creatingfilters angular.module('MyFilterModule', []). filter('myfilter', function() { return function(input) { ... return output; }; }); MAINCONCEPTS/FILTERS /56 Read More: https://docs.angularjs.org/guide/filter User the filter provider to create a new filter in the module Name the filter Return the filter function. The first argument is the input value. Additional arguments can be used.
  • 36. 36Services  Reusablebusiness logiccomponentes,independentof views,wired togetherusing dependencyinjection(DI).  Singletonsgeneratedby a servicefactory.  Angular only instantiatesa serviceif thereis a dependencyfor it.  Built-in servicesstart with $. Examples:$log, $http, $filter,$exceptionHandler MAINCONCEPTS /56 Read More: https://docs.angularjs.org/guide/services
  • 37. 37Usingaservice var countryApp = angular.module('countryApp', []); countryApp.controller('CountryCtrl', ['$scope', '$http', function (scope, http) { http.get(‘countries.json').success(function(data) { scope.countries = data; }); }]); MAINCONCEPTS/SERVICES /56 Inject $http service using DI Receive service object as a parameter Call method on service Read More: https://docs.angularjs.org/guide/services
  • 38. 38Creatingaservice var myModule = angular.module('myModule', []); myModule.factory('serviceId', function() { var shinyNewServiceInstance; //factory function body that constructs shinyNewServiceInstance return shinyNewServiceInstance; }); MAINCONCEPTS/SERVICES /56 Return a service instance Register a new factory function for the service Read More: https://docs.angularjs.org/guide/services
  • 39. 39Recipes var myApp = angular.module('myApp',[]); myApp.provider('MyFactory', function() {...}); myApp.factory('MyFactory', function() {...}); myApp.service('MyFactory', function() {...}); myApp.constant('MyConstant', 'My Constant Value'); myApp.value('MyValue', 35); MAINCONCEPTS/SERVICES /56
  • 41. 41Multipleviews  Most applicationsarecomposedof morethan one view  In Single PageApplicationsall viewsare renderedin the same page (LayoutTemplate)which containsall the commonpage elements  Eachview(PartialTemplate)is placedin its own file and dynamically loadedinto the LayoutTemplate page MAINCONCEPTS /56
  • 42. 42Multipleviews MAINCONCEPTS /56 index.html header.html a1.html b2.html a2.html b1.html b3.html a3.html Layout Template Partial Template Partial Template Partial Template Partial Template
  • 43. 43Routing  Routing is providedby the ngRoute module(separatedistribution)  Routesare declaredvia the $routeProvider fromthe $route service  Supports deeplinking(history,bookmarksand browserback/forward buttons)  Partialviewsarerenderedby the ngView directive MAINCONCEPTS /56
  • 44. 44Routingconfiguration var myApp = angular.module('myApp',['ngRoute']); myApp.config(['$routeProvider', function($routeProvider) { $routeProvider. when('/phones', { templateUrl: 'partials/phone-list.html', controller: 'PhoneListCtrl‘ }). when('/phones/:phoneId', { templateUrl: 'partials/phone-detail.html', controller: 'PhoneDetailCtrl' }). otherwise({ redirectTo: '/phones' }); }]); MAINCONCEPTS/ROUTING /56 Route Dependency on ngRoute module Default Route Route with variable URL. PhoneId value will be placed in $routeParams object
  • 47. 47BestPractices  In Views/Templates  Usedirectivesforabstractingcommonmarkups,extensions  Donotusecomplexexpressionsinbindings.Movethemtocontrollers.  Optimizeuseofbindings.Lessbindings=fasterapplication.  In Controllers  Keepthemlight.Useservicestooffloadfunctionality.  NoDOMmanipulations!Usedirectivesforthat. /56
  • 48. 48BestPractices  In Directives  Preferusingdirectivesaselementsorattributesoverclassesandcomments  Donotng-prefixforyourdirectives  Createisolatescopestoavoidacidentaloverridesofproperties  Createmodulesto group controllers,services,directivesand filters /56
  • 49. Tools
  • 50. 50Tools  IDE: Visual Studio, NetBeans,WebStorm  Utils: JSFiddle, BatarangPlugin for Chrome  Static Code Analysis:JSHint  Unit Testing: Karma /56
  • 52. 52Wrappingup  AngularJS is a modular JavaScriptSPA framework  Has a lot of great featuresbut a steeplearningcurve  Greatfor CRUD applicationsbut not suitable for everytype of application  Worksvery wellwith some JavaScriptlibraries(such as jQuery)but not so wellwith others  Increasesdeveloperproductivity in small/medium applicationsbut can be quite heavyfor complexapplications /56
  • 53. 53Nexttime...  Custom directives  Formcontrolsand validation  Unit testing  End-to-endtesting  Animations WRAPPINGUP /56
  • 54. 54Resources Officialdocumentation  Projecthomepage:https://angularjs.org/  DeveloperGuide:https://docs.angularjs.org/guide  Tutorial:https://docs.angularjs.org/tutorial  APIReference:https://docs.angularjs.org/api  BuiltwithAngular:https://builtwith.angularjs.org Trainingvideosandtutorialsfordevelopers  Egghead:https://egghead.io/technologies/angularjs Additionalstuff  Angularmodules:http://ngmodules.org/ WRAPPINGUP /56