Produced by
Department of Computing & Mathematics Waterford Institute of Technology
http://www.wit.ie
Web Application Development David Drohan ([email protected])
FILTERS, SERVICES & DIRECTIVES
PART 3
Sec4on Outline 1. Introduc)on–WhyyoushouldbeusingAngularJS
2. Terminology–Thecri:calfounda:onforunderstanding
3. Modules–Reusablefunc:onality
4. Views–UI(UserInterac:on)
5. Controllers–Facilita:ngcommunica:onbetweenthemodelandtheview
6. Routes–Naviga:ngtheview
7. Filters–Changingthewayyouseethings
8. Services–Fiverecipeflavors
9. Direc)ves–ExtendingHTML
10. CaseStudy–Labsinac:on11. Conclusions–Theendisnigh
03ANGULARJS-PART3 3
Sec4on Outline 1. Introduc)on–WhyyoushouldbeusingAngularJS
2. Terminology–Thecri:calfounda:onforunderstanding
3. Modules–Reusablefunc:onality
4. Views–UI(UserInterac:on)
5. Controllers–Facilita:ngcommunica:onbetweenthemodelandtheview
6. Routes–Naviga:ngtheview
7. Filters–Changingthewayyouseethings8. Services–Fiverecipeflavors9. Direc)ves–ExtendingHTML10. CaseStudy–Labsinac:on
11. Conclusions–Theendisnigh03ANGULARJS-PART3 4
Basic Building Blocks WHAT YOU NEED TO BUILD A BASIC ANGULAR WEB APP
03ANGULARJS-PART3 5
Filters CHANGING THE WAY YOU SEE THINGS
03ANGULARJS-PART3 6
Filters Whatisafilter:◦ Afilterformatsthevalueofanexpressionfordisplaytotheuser.◦ (h]ps://docs.angularjs.org/guide/filter)
FilterscanbeusedinHTMLusingthebarnota:onortheycanbeusedinJavaScriptbyinjec:ngthe$filterservice.
03ANGULARJS-PART3 7
Filters HTMLEXAMPLE JAVASCRIPTEXAMPLE
var module = angular.module('myApp', []); module.controller('myController', [ '$scope', '$filter', function($scope, $filter) { $scope.name = 'John Smith'; $scope.uppercaseName = function() { return $filter('uppercase')($scope.name); }; }]);
<div ng-app='myApp' ng-controller="myController"> <p>{{name | uppercase}}</p> <p>{{uppercaseName()}}</p> </div>
03ANGULARJS-PART3 8
Filters with Parameters HTMLEXAMPLE JAVASCRIPTEXAMPLE
{{ expression | filterName : param1 : param2 }} $filter('filterName')(expression, param1, param2);
03ANGULARJS-PART3 9
Core Filters AngularJShasseveralfiltersbuiltin:◦ currency◦ date◦ filter◦ json◦ limitTo◦ lowercase◦ number◦ orderby◦ uppercase
{{ '2015-03-19T19:00:00.000Z' | date : 'MMMM yyyy' }}
$filter('date')(new Date(), 'MMMM yyyy');
03ANGULARJS-PART3 10
Core Filters AngularJShasseveralfiltersbuiltin:◦ currency◦ date◦ filter◦ json◦ limitTo◦ lowercase◦ number◦ orderby◦ uppercase
{{ ['pear', 'apple', 'orange'] | filter : 'r' }}
$filter('filter')(['pear', 'apple', 'orange'], 'r');
03ANGULARJS-PART3 11
Selectasubsetofanarrayfordisplay
Core Filters AngularJShasseveralfiltersbuiltin:◦ currency◦ date◦ filter◦ json◦ limitTo◦ lowercase◦ number◦ orderby◦ uppercase
{{ { first: 'John', last: 'Smith } | json }}
$filter('json')({ first: 'John', last: 'Smith'});
03ANGULARJS-PART3 12
Formatinjsonforeasysearching
Core Filters – More Examples
03ANGULARJS-PART3 13
{{‘hello’|uppercase}} àHELLO
{{2000|currency}} à$2,000.00
{{2500|currency:’EUR€’}}{{1288323623006|date}}
àEUR€2,500.00àOct29,2010
{{1288323623006|date:’dd/MM/yyyy’}} à29/10/2010{{1288323623006|date:’EEEdd/MM/yy’}}àFri29/10/10
Core Filters
03ANGULARJS-PART3 14
Filterscanbechained/stacked(wheresensible)
1. customers|orderBy:’-balance'|limitTo:2---onlyshowthetwo
richestcustomers2. customers|filter:{name:’ki’}|orderBy:’-balance'|limitTo:5
thefiverichestcustomerswhosenamecontainsthesubstring‘ki’.
Core Filters – Our Example
03ANGULARJS-PART3 15
Filter Defini4on Youcandefineanewfilterwithinamodule.angular.module('reverseFilter', []) .filter('reverse', [function() { return function(input, uppercase) { var i, out = ""; input = input || ''; for (i = 0; i < input.length; i++) { out = input.charAt(i) + out; } // conditional based on optional argument if (uppercase) { out = out.toUpperCase(); } return out; }; }]);
$filter('reverse')('Hello, World!', true);
{{ 'Hello, World!' | reverse : true }}
03ANGULARJS-PART3 16
Services FIVE RECIPE FLAVORS
03ANGULARJS-PART3 17
AngularJS Services Servicesprovideamethodforustokeepdataaroundforthelife:meoftheappandcommunicateacrosscontrollersinaconsistentmanner. Servicesaresingletons,whichareobjectsthatareinstan:atedonlyonceperapp(bythe$injector).Theyprovideaninterfacetokeeptogethermethodsthatrelatetoaspecificfunc:on. Angularcomeswithseveralbuilt-inservices,ofdifferenttypes(orrecipes)whichwe’llcoverinthenextfewslides. Youcanalsomakeyourownservicesforanydecentlycomplexapplica:on.
03ANGULARJS-PART3 18
Value Thevaluerecipestoresavaluewithinaninjectableservice. Avaluecanstoreanyservicetype:astring,anumber,afunc:on,andobject,etc.
Thisvalueofthisservicecannowbeinjectedintoanycontroller,filter,orservice.//define a module var myModule = angular.module('myModule', []); //define a value myModule.value('clientId', 'a12345654321x'); //define a controller that injects the value myModule.controller('myController', ['$scope', 'clientId', function ($scope, clientId) { $scope.clientId = clientId; }]);
03ANGULARJS-PART3 19
Factory Thefactoryrecipeissimilartoavaluerecipeexceptthatitaddstheseabili:es:◦ Abilitytousedependencyinjec:on◦ Lazyini:aliza:on
Afactory(likeavalue)canalsoreturnanydatatype.//define a factory myModule.factory('toUpperCase', ['$filter', function($filter) { return function(value) { return $filter('uppercase')(value); } }]); //inject the toUpperCase factory myModule.controller('myController', ['toUpperCase', function(toUpperCase) { this.uppercase = toUpperCase('john'); }]);
03ANGULARJS-PART3 20
Service Justtomakethingsali]leconfusing,wehaveaservicerecipecalledservice.
◦ Yes,wehavecalledoneofourservicerecipes'Service'.Weregretthisandknowthatwe'llbesomehowpunishedforourmisdeed.It'slikewenamedoneofouroffspring'Child'.Boy,thatwouldmesswiththeteachers.(h]ps://docs.angularjs.org/guide/providers)
03ANGULARJS-PART3 21
Service Theservicerecipewillgenerateasingletonofaninstan:atedobject.//define a service myModule.service('person', [function() { this.first = 'John'; this.last = 'Jones'; this.name = function() { return this.first + ' ' + this.last; }; }]); //inject the person service myModule.controller('myController', ['$scope', 'person', function($scope, person) { $scope.name = person.name(); }]);
03ANGULARJS-PART3 22
Provider “…theProviderrecipeisthecorerecipetypeandalltheotherrecipetypesarejustsyntac:csugarontopofit.Itisthemostverboserecipewiththemostabili:es,butformostservicesit'soverkill”
(h]ps://docs.angularjs.org/guide/providers). Theproviderrecipecanbeinjectedduringamodule’sconfigura:onphase.
03ANGULARJS-PART3 23
Provider
03ANGULARJS-PART3 24
//define a provider myModule.provider('prefix', [function() { var prefix = ''; //setPrefix can be called during the module's config phase this.setPrefix = function(value) { prefix = value; }; //this special property is required and returns a factory this.$get = [function() { return function(value) { return prefix + value; } }]; }]); //inject the provider in the config phase myModule.config(['prefixProvider', function(prefixProvider) { prefixProvider.setPrefix('John '); }]); //inject the provider's factory myModule.controller('myController', ['prefix', function(prefix) { this.value = prefix('Smith'); //value is set to "John Smith" }]);
Constant Theconstantrecipeissimilartothevaluerecipeexceptthatitsservicevalueisalsoavailableduringthemodule’sconfigura:onphase.
myModule.constant('author', 'John Smith'); myModule.config(['author', function(author) { console.log('This app was made by: ' + author); // "John Smith" }]); myModule.controller('myController', ["author", function (author) { this.author = author; // "John Smith" }]);
03ANGULARJS-PART3 25
Direc4ves EXTENDING HTML
03ANGULARJS-PART3 26
Direc4ves Whatisit?◦ Atahighlevel,direc:vesaremarkersonaDOMelement(suchasana]ribute,elementname,commentorCSSclass)thattellAngularJS'sHTMLcompiler($compile)toa]achaspecifiedbehaviortothatDOMelementoreventransformtheDOMelementanditschildren.
◦ (h]ps://docs.angularjs.org/guide/direc:ve)<form> <p> Enter your name: <input type="text" ng-model="name" required> <button type="button" ng-click="submit()" ng-disabled="!name">Submit</button> </p> <p ng-show="name"> Hello, {{name}} </p> </form>
03ANGULARJS-PART3 27
Direc4ves Direc:vesextendHTMLtosuittheneedsofdynamicwebapp(SPA)development§ ng-app§ ng-model§ ng-repeat§ ng-controller§ ng-init§ etc
Customdirec:vesalsosupportedRecallour2-waydatabinding
03ANGULARJS-PART3 28
Direc4ve Documenta4on (for wri4ng your own!) Forfulldocumenta:ononhowtowritedirec:ves,seethesepages:
h]ps://docs.angularjs.org/guide/direc:ve
h]ps://docs.angularjs.org/api/ng/service/$compile
03ANGULARJS-PART3 29
Case Study LABS IN ACTION
03ANGULARJS-PART3 30
Demo Applica4on
03ANGULARJS-PART3 31
Conclusions THE END IS NIGH
03ANGULARJS-PART3 32
Essen4als for Building Your First App HTMLDOCUMENT APP.JS
var module = angular.module('app', ['moduleA']); <!doctype html> <html lang="en" ng-app="app"> <head> <title>App Title</title> <link rel="stylesheet" href="css/styles.css"> </head> <body> <script src="js/angular.js"></script> <script src="js/app.js"></script> <script src="js/moduleA.js"></script> </body> </html>
03ANGULARJS-PART3 33
Great Resources OfficialTutorial–h]ps://docs.angularjs.org/tutorial
OfficialAPI–h]ps://docs.angularjs.org/api
DeveloperGuide–h]ps://docs.angularjs.org/guide VideoTutorials–h]ps://egghead.io/
VideoIntroduc:on–h]ps://www.youtube.com/watch?v=i9MHigUZKEM
YouTubeChannel–h]ps://www.youtube.com/channel/UCm9iiIfgmVODUJxINecHQkA
Ar:cles,explana:ons,tutorials–h]p://www.ng-newsle]er.com/
03ANGULARJS-PART3 34
About the Original Author JamesSpeirs
Applica:onFounda:ons
OITCoreServices BrighamYoungUniversity
03ANGULARJS-PART3 35
Questions?
03ANGULARJS-PART3 36