Working with AngularJS

1,504
-1

Published on

Introductory session about AngularJS, delivered on May 20th 2014 at Microsoft Web Camp, in Lisbon, Portugal.

Published in: Technology, Business

Working with AngularJS

  1. 1. Workingwith Microsoft WebCamp 2014 May 20, 2014
  2. 2. 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
  3. 3. 3Agenda  What is AngularJS?  Main Concepts  Tools  BestPractices  Wrappingup /56
  4. 4. WhatisAngularJS?
  5. 5. “Angular is what HTML would have been had it been designed for applications.” Miško Hevery
  6. 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. 7. 7History  Createdby MiškoHevery  Opensourcesince2009  Supportedby Google  Large and fast-growingcommunity WHATISANGULARJS? /56
  8. 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. 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
  10. 10. 10Trendingtopic WHATISANGULARJS? /56 Source: Google Trends
  11. 11. 11Learningcurve WHATISANGULARJS? /56
  12. 12. MainConcepts
  13. 13. 13Mainconcepts  Templates  Directives  Expressions  Data binding  Scope /56  Controllers  Modules  Filters  Services  Routing
  14. 14. HelloWorld DEMOMAINCONCEPTS
  15. 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. 16. 16Templates  HTML with additional markup  Directives  Expressions  Filters  Formcontrols MAINCONCEPTS /56 Read More: https://docs.angularjs.org/guide/templates
  17. 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. 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. 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. 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
  21. 21. Expressions DEMOMAINCONCEPTS
  22. 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
  23. 23. Two-waydatabinding DEMOMAINCONCEPTS
  24. 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. 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. 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. 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
  28. 28. Usingcontrollers DEMOMAINCONCEPTS
  29. 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
  30. 30. Usingmodules DEMOMAINCONCEPTS
  31. 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. 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. 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. 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.
  35. 35. Usingfilters DEMOMAINCONCEPTS
  36. 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. 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. 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. 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
  40. 40. Usingservices DEMOMAINCONCEPTS
  41. 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. 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. 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. 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
  45. 45. Routing DEMOMAINCONCEPTS
  46. 46. Bestpractices
  47. 47. 47BestPractices  In Views/Templates  Usedirectivesforabstractingcommonmarkups,extensions  Donotusecomplexexpressionsinbindings.Movethemtocontrollers.  Optimizeuseofbindings.Lessbindings=fasterapplication.  In Controllers  Keepthemlight.Useservicestooffloadfunctionality.  NoDOMmanipulations!Usedirectivesforthat. /56
  48. 48. 48BestPractices  In Directives  Preferusingdirectivesaselementsorattributesoverclassesandcomments  Donotng-prefixforyourdirectives  Createisolatescopestoavoidacidentaloverridesofproperties  Createmodulesto group controllers,services,directivesand filters /56
  49. 49. Tools
  50. 50. 50Tools  IDE: Visual Studio, NetBeans,WebStorm  Utils: JSFiddle, BatarangPlugin for Chrome  Static Code Analysis:JSHint  Unit Testing: Karma /56
  51. 51. Wrappingup
  52. 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. 53. 53Nexttime...  Custom directives  Formcontrolsand validation  Unit testing  End-to-endtesting  Animations WRAPPINGUP /56
  54. 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
  55. 55. ThankYou! Downloadslidedeck:http://1drv.ms/1h1YOlS Downloaddemos:http://1drv.ms/1h1YJyP
  1. A particular slide catching your eye?

    Clipping is a handy way to collect important slides you want to go back to later.

×