AngularJS One Day Workshop

  • Published on

  • View

  • Download


Slides for the one day AngularJS workshop conducted at JsFoo 2014


<ul><li> 1. AngularJS WorkshopJSFoo 2014Shyam Seshadri</li></ul> <p> 2. Most Important WIFI Network HasGeek-Wifi (If you can see this) HasGeek (Otherwise) WIFI password geeksrus Open Clone the repository locally open the folder created, and run npm install 3. Introduction Ex Googler Author AngularJS for OReilly AngularJS Up &amp; Running for OReilly Entrepreneur Coder / Geek 4. Agenda 1 day 4 Sessions Beginning to App in 16 Steps Hands on Questions? Try &amp; save them for end of eachsession 5. Agenda (contd)Session 1 Introduction &amp; History Basic Concepts &amp;TerminologiesWorking withControllers Angular ServicesWorking with AngularJSinbuilt servicesSession 2 Creating your ownservices Introduction to $http Promises in AngularJS Routing 6. Agenda (contd)Session 3 Introduction toTesting inAngularJS Unit Testing inAngular End to End testingSession 4 Introduction toDirectives Creating your owndirectives Best Practices 7. Requirements1. NodeJS ( Karma (npm install g karma-cli)3. Protractor (npm install g protractor)4. Webstorm( -OPTIONAL 8. Github Repo 9. Code Along Initial SetupCheckout:git clone angularjs-one-dayRun:npm install 10. Expectations You will not be an expert at the end!! Live, hands-on but as much as time permits Questions, as much as possible Touch upon each and every part of AngularJS Follow along as best Jump steps if falling behind 11. Expectations - continued One full app, from start to finish Simple, Todolist No Complex Directives No Login / Auth flows We will cover unit testing But gloss over end to end tests Try out things, break things Thats how we learn! 12. Suggestions Use Google Chrome Faster One of the best Web Development Tools If something doesnt work Look at the console (in Development Tools) Look for typos Check against the next step 13. SESSION 1 INTRODUCTION &amp;BASICS 14. Agenda MVC &amp; the Web Introducing AngularJS Basic Concepts Terminologies Working with Controllers 15. The Changing Web ParadigmComplexity Shift 16. The need to manage complexityData Retrieval Biz. LogicAuthorization&amp; PermissionsRenderingConcurrentusageAnd so muchmore 17. While hitting faster turnaround timesFeature 1Deliver in 10 weeksFeature 2Deliver in 2 weeksFeature 3Deliver yesterday!!!So how can we even attempt to do this? 18. The need for Structure Modularity Tests Speed of Development 19. Before AngularJS GWT Do it all in Java jQuery + JS Each project is different How do you test DOM manipulation? Dependent on Engineers, not on frameworks 20. Introducing . A MVC framework for the Web No need for a new templating language uses HTML Two Way Databinding between View &amp; Code Allows Reusable HTML components Directives Separation of concerns Routing, Deep Linking, History Unit Testing framework built-in 21. The AngularJS MVC patternThe Model is fetched andmanipulated by thecontrollerModel gets rendered tothe User as the ViewModelView ControllerUser Actions inthe view aretriggered in thecontroller 22. Model-V-C 23. A Simple Model in AngularJSJust any JSON object returned by the Server 24. M-View-C 25. Template +Scope =&gt; ViewProjectionof theModelCan be styledindependentlyDerivesbehavior fromController 26. M-V-Controller 27. The Controller is responsible forFetchingdata fromthe serverExposingdata to viewthroughScopeHandlingUserinteractionslike clicksAny otherbiz. logic 28. Data BindingjQuery only world </p> <p> $(#nameTxt).text(nameVar); nameVar.onChange(function(newVal, oldVal) {// Update #nameTxt}); If an input field, then additional $(#nameInp).change(function() {nameVar = $(#nameInp).val();});AngularJS world {{nameVar}} 29. Create your own componentsjQuery only worldAngularJS worldWhat if we could just do this?content herecontent herePlus the content, and the logic ofSwitching between the tabs, and somuch more. 30. RoutingIn JS, for deep linking, we need to: Have a state machine Have an allotted view which changes Manage addition and removal from history Attach the right controller and scope with each view Potentially load all content before displayingAll of that with a simple API, as part of ngRoute 31. Server communicationAll the standards of $, plus Caching Configurability ResourcesDefine a Project as And then call Project.delete() And more 32. Dependency InjectionThe concept of asking for dependencies, rather than creatingthemA Service / factory is responsible for creating and providing yourdependencies (known as the injector) WhatTestabilitySeparation of concernsDeclarativeReusability WhyEverywhere in AngularJS From Controllers to Services, from Directives to Filters Where 33. Dependency Injection 34. TestingDO IT! 35. TestingUnit Tests Test the individual functions Expected return values Side effects Focused, Specific Mocks out larger systembehaviorScenario Tests End to End Starts up a real browser Behaves like a user Can have a real serverbacking it 36. A Sample Unit test 37. Backend Requirements The same requirements that jQuery has Nothing! Easier if it talks JSON But not required Works well with Java, as well as with Ruby onRails Needs a way of communicating to the server Concept of transforming requests and responses No JSON? No problem! 38. Do I need to develop my entire app inAngularJS? Has the concept of ng-app Denote a section of the page Can integrate as a section in an existing app Can run it beside an existing app Some URLs handled by AngularJS Can expand over time, gradually 39. Whos using AngularJS? Google (of course!) Double Click for Advertisers Youtube And many more Amazon Netflix ING Lots of startups 40. Future Plans Object.observable to replace dirty checking Web components / Shadow DOM integration Asynchronous Loading Http, Socket, Offline, much more Mobile first 41. AngularJS + Mobile Attributes / Interpolated Strings &amp; binding -&gt; Functions 149. The Compile function DOM transformations Common to all instances of directive Think ng-repeat Think ng-view No Scope yet 150. The Linking Function Ability to add specific behavior When your directive is first loaded For future behavior, restricted to the element Run once for each instance of your element 151. Directive Controllers Controller functions for your directive Used for cross directive communication Use Link When you have functionality specific to yourdirective Use Controller When you have functionality that other directives(usually child) will need to access 152. Transclusions Customized content for directives Changes from usage to usage Think Tabs Think Zippy / Accordions Think Carousels 153. SESSION 4 CODE-ALONGCONTINUES 154. Code Along Session 4 Convert ng-include todirective step14 Convert directive to fullycontained with data passed in step15step16 Delete todo and reload list 155. Step 14 - Converting ng-include todirective Create directive todoWidget Use as todo-widget in HTML Return Directive definition object Restrict: A templateUrl: components/todo-widget/todo-widget.html 156. Step 15 - Self contained directives Scope param = binding todo: =todoData Takes todo-data in HTML, saves it as $scope.todo Link function Gets three arguments - $scope, $element, $attrs getTodoClass function on $scope 157. Step 16 Delete todo and reload list Add del function in todo-service $http[delete](/api/todo + id); Add button in todo-widget.html ng-click=deleteTodo() In directive Add deleteTodo() function which calls service Add whenDelete: &amp; in scope attribute On success of service call, call $scope.whenDelete() In LandingCtrl Add reload function In HTML, add when-delete=lCtrl.reload() 158. BACK TO THEORY 159. BEST PRACTICES, MODULES, TOOLS 160. 10 DOS AND 10 DONTS INANGULARJS 161. DO #1: WRITE YOUR UNIT TESTS(AND SCENARIO TESTS) 162. DO #2: LEVERAGE DATA BINDING 163. DO #3: WRAP 3RD PARTY COMPONENTSAS DIRECTIVES / SERVICES 164. DO #4: USE MODULES &amp; ORGANIZECODE BY FUNCTIONALITY 165. DO #5: USE TRACK BY FOR NG-REPEAT 166. DO #6: NAMESPACE YOUR CODE 167. DO #7: USE MULTIPLE LAYERS FORSERVICES 168. DO #8: MINIMIZE DATA ON SCOPE /THIS 169. DO #9: USE THE CONTROLLER ASSYNTAX 170. DO #10: USE RESOLVE FOR PRE-ROUTECHECKS &amp; INTERCEPTORS FOR ALLOTHERS 171. DONT #1: USE $ROOTSCOPE AS ASTORE. DONT USE $SCOPE TO SHAREFUNCTIONS &amp; VARIABLES 172. DONT #2: DOM MANIPULATION INCONTROLLER 173. DONT #3: OVERUSE FILTERS INYOUR HTML 174. DONT #4: PUT DATA YOU DONTSHOW ON SCOPE / THIS 175. DONT #5: MANIPULATE THE UIDIRECTLY 176. DONT #6: USE GLOBAL SELECTORSIN DIRECTIVES 177. DONT #7: GO OVERBOARD WITHNG-REPEATS 178. DONT #8: OVERUSE SCOPE EVENTSIN YOUR APPLICATION 179. DONT #9: FORGET CLEANUP INYOUR CONTROLLERS &amp; DIRECTIVES 180. DONT #10: CREATE GIANT FILES ORFOLDERS 181. Other modules Animation Touch Cookies Resource Security Routing 182. BEST PRACTICES 183. Directory Structure Yeoman / Angular seed App images css Vendors (libs) sections components Tests Spec Mimic js folder structure E2e Reflect app heirarchy 184. Modularizing your codebase What can be reused? What belongs in logical groups? Group by functionality, not by type 185. Build Process Grunt / Ant Glob / Minify your code base Load at the end of body Cache static files Namespace by version Use Etags ng-boilerplate is a great starting point 186. RequireJS Good Can be overkill Lot of extra boilerplate Great for lazy loading dependencies Beneficial only if you have hundreds of files 187. Dependency Injection Use it Depend on it Use the [] notation (more on this later) Capture external dependencies in Services Use Mocks to inject dependencies in tests Look at ng-annotate if you want to be lazy 188. 3rd party callbacks &amp; $applyDo Use 3rd party libraries andcomponents Integrate them as directives/ services when possibleDont Forget to call $apply to letangular know when to dowork 189. Handling Data &amp; ACLs Resolve Load Data Handle auth checks Login or not? Interceptors Per request level 190. Flashing {{}} in HTML Use ng-cloak Use ng-bind instead of {{ }} 191. Syntax Use module. Syntax Use safe DI Namespace as much as possible 192. Putting things on $scope Minimize What the view needs only! The scope is heavy and expensive Every item gets digested and dirty checked Think twice, and thrice first 193. The $rootScopeDO NOT Use the root scope to store global state Use the root scope as a communicationmechanism In fact, forget there is a parent $rootScope ifat all possibleValid Uses: Broadcasting and listening for events 194. Communicating in the App Services Scope $broadcast, $emit and $on URL Params 195. Attribute Directives You can create directives that are Attributes (like ng-show, ng-hide) Elements () Classes (</p> <div>) Comments () But Always prefer to use attributes or classes IE compatibility issues! 196. Structuring Business LogicControllers should not reference DOM should have view behavior What should happen if user does X Where do I get X from?Services should not reference DOM (mostly) are singletons have logic independent of view Do X operationPS: Do put DOM manipulation in Directives 197. Using the [] for DImyApp.controller(MyCtrl, function($scope, $location) {});Is the same asmyApp.controller(MyCtrl, [$scope, $location, function($scope, $loc) {}]); 198. Using the [] for DIUntil you compile your code!myApp.controller(MyCtrl, function(a, xy) {});Is not the same asmyApp.controller(MyCtrl, [$scope, $location, function(a, xy) {}]);[] notation is the only way AngularJS knows whichparams are which! 199. To $ or not to $ $ is used by AngularJS internals only $scope $http $resource Dont use $ when you are naming your ownservices, controllers, etc. 200. USEFUL TOOLS &amp; LIBRARIES 201. Batarang 202. Karma + Webstorm 203. 3rd Party Components Wijmo KendoUI Angular-UI 204. Other Tools Yeoman Ng-Boilerplate 205. SO IN SUMMARY 206. Feedback Feedback? Comments? Suggestions? omniscient1 on Twitter Recommend us on LinkedIn (FundooSolutions) if you like it </div>