AngularJS Essentials - GitHub Pages

3y ago
63 Views
4 Downloads
1.08 MB
180 Pages
Last View : Today
Last Download : 3m ago
Upload by : Brenna Zink
Transcription

AngularJS EssentialsDesign and construct reusable, maintainable, andmodular web applications with AngularJSRodrigo BranasBIRMINGHAM - MUMBAI

AngularJS EssentialsCopyright 2014 Packt PublishingAll rights reserved. No part of this book may be reproduced, stored in a retrievalsystem, or transmitted in any form or by any means, without the prior writtenpermission of the publisher, except in the case of brief quotations embedded incritical articles or reviews.Every effort has been made in the preparation of this book to ensure the accuracyof the information presented. However, the information contained in this book issold without warranty, either express or implied. Neither the author, nor PacktPublishing, and its dealers and distributors will be held liable for any damagescaused or alleged to be caused directly or indirectly by this book.Packt Publishing has endeavored to provide trademark information about all of thecompanies and products mentioned in this book by the appropriate use of capitals.However, Packt Publishing cannot guarantee the accuracy of this information.First published: August 2014Production reference: 1140814Published by Packt Publishing Ltd.Livery Place35 Livery StreetBirmingham B3 2PB, UK.ISBN 978-1-78398-008-6www.packtpub.com

CreditsAuthorRodrigo BranasReviewersProject CoordinatorAboli AmbardekarProofreadersAndrei M. EichlerSimran BhogalCleberson C. C. FaccinMaria GouldRuoyu SunAmeesha GreenFelipe TrevisolPaul HindleCommissioning EditorPramila BalanIndexersMariammal ChettiyarRekha NairAcquisition EditorHarsha BharwaniContent Development EditorSharvari TawdeTechnical EditorsShiny PoojaryKirti PujariAkash Rajiv SharmaPriya SubramaniGraphicsRonak DhruvDisha HariaProduction CoordinatorAlwin RoyCover WorkAlwin RoyCopy EditorsRoshni BanerjeeMradula HegdeAlfida PaivaCover ImageYuvraj Mannari

About the AuthorRodrigo Branas is a software architect, author, and international speaker onsoftware development based in Brazil, with more than 12 years of experience indeveloping enterprise applications.Lately, he has been participating in the development of many successful productsbased on the AngularJS framework. A major part of these applications were madeavailable to the education industry, and are now used by thousands of users acrossthe country.He is also the founder of Agile Code, a consultancy and training company that workseffectively with architects, developers, designers, and testers in order to producehigh-quality products.He graduated in Computer Science and has an MBA degree in Project Management.He is certified in SCJA, SCJP, SCJD, SCWCD, and SCBCD from Sun Microsystems;PMP from Project Management Institute; MCP from Microsoft; and CSM fromScrum Alliance.In the past few years, he has dedicated himself to spreading knowledge in thesoftware development community. Also, he is the author of Java Magazine, one of themost recognized technical publications in Brazil. His website address is http://www.agilecode.com.br. He can be contacted at rodrigo.branas@gmail.com and youcan follow him on Twitter at @rodrigobranas.

AcknowledgmentsWriting this book was an incredible challenge! Throughout this time, I had thepleasure to count on my lovely wife, Rosana Branas, who provided me with all theinspiration, motivation, and affection that I needed.Also, I am very happy and glad about sharing this experience with my reviewers:Felipe Trevisol, Cleberson Faccin, Andrei Eichler, and Ruoyu Sun. They provided mewith their views, which I feel were quite important, and advice that helped improvethe text considerably.I also would like to thank my great friend, Rafael Nami, who introduced me to theAngularJS world, helping me during my first steps with this amazing technology.Special thanks to the outstanding editorial team at Packt Publishing: Ankita Goenka,Aboli Ambardekar, Harsha Bharwani, Sharvari Tawde, Shiny Poojary, Kirti Pujari,and Veena Manjrekar.Finally, this book would not be complete without the support of my family! I wouldespecially like to thank my mom and dad, for the continuous love, education,support, and encouragement that they have always provided me!

About the ReviewersAndrei M. Eichler is a young developer with a great passion for learning. Hismain experiences include working with large Postgres databases and Java, and he isnow venturing into Scala, performant JavaScript, and web application development.Cleberson C. C. Faccin is a graduate in Systems Information from UniversidadeFederal de Santa Catarina, Brazil. Since 2004, he has been working in the fieldof software development. During these 10 years, he has worked with severaltechnologies, from mainframes to applications of mobile devices. Currently, hisfocus is on his work in JavaScript, where he is building applications for mobileswith JavaScript.Ruoyu Sun is a designer and developer living in Hong Kong. He is passionateabout programming and has contributed to several open source projects. He is thefounder of several tech start-ups using a variety of technologies before working inthe industry. He is the author of Designing for XOOPS, O'Reilly Media.I would like to thank all my friends and family who have alwayssupported me.Felipe Trevisol is a software architect who loves research, travel, and playingguitar. He has worked with SOA and systems integration.

www.PacktPub.comSupport files, eBooks, discount offers,and moreYou might want to visit www.PacktPub.com for support files and downloads related toyour book.Did you know that Packt offers eBook versions of every book published, with PDF and ePubfiles available? You can upgrade to the eBook version at www.PacktPub.com and as a printbook customer, you are entitled to a discount on the eBook copy. Get in touch with us atservice@packtpub.com for more details.At www.PacktPub.com, you can also read a collection of free technical articles, sign up for arange of free newsletters and receive exclusive discounts and offers on Packt books and eBooks.TMhttp://PacktLib.PacktPub.comDo you need instant solutions to your IT questions? PacktLib is Packt's online digital booklibrary. Here, you can access, read and search across Packt's entire library of books.Why subscribe? Fully searchable across every book published by Packt Copy and paste, print and bookmark content On demand and accessible via web browserFree access for Packt account holdersIf you have an account with Packt at www.PacktPub.com, you can use this to accessPacktLib today and view nine entirely free books. Simply use your login credentialsfor immediate access.

Table of ContentsPrefaceChapter 1: Getting Started with AngularJS17Introduction to AngularJSArchitectural conceptsSetting up the frameworkOrganizing the codeFour ways to organize the code89101213Summary15The inline styleThe stereotyped styleThe specific styleThe domain styleChapter 2: Creating Reusable Components with DirectivesWhat is a directive?Using AngularJS built-in directivesThe ngApp directiveThe ngController directiveNested controllersThe ngBind directiveThe ngBindHtml directiveThe ngRepeat directiveThe ngModel directiveThe ngClick directive and other event directivesThe ngDisable directiveThe ngClass directiveThe ngOptions directiveThe ngStyle directiveThe ngShow and ngHide directives1313141517181919202121222224252627283030

Table of ContentsThe ngIf directiveThe ngInclude directiveRefactoring application organizationCreating our own ranscludelinkrequirecontrollercompileAnimationHow it works?Animating ngRepeatAnimating ngHideAnimating ngClassSummaryChapter 3: Data HandlingExpressionsFiltersBasic usage with berorderByuppercaseUsing filters in other placesCreating filtersForm validationCreating our first formBasic validationUnderstanding the pristine and dirty propertiesThe error objectSummary[ ii ]5556565758585859606061626263656566

Table of ContentsChapter 4: Dependency Injection and ServicesDependency injectionCreating servicesCreating services with the factoryCreating services with the serviceCreating services with the providerUsing AngularJS built-in servicesCommunicating with the backendHTTP, REST, and JSONCreating an HTTP 82848585Creating a single-page application87LoggingTimeoutAsynchronous with a promise-deferred pattern969698Installing the moduleConfiguring the routesRendering the content of each viewPassing parametersChanging the locationResolving promisesThe deferred APIThe promise APISummary878788919293100101101Chapter 5: Scope103Chapter 6: Modules115Two-way data binding apply and watchBest practices using the scopeThe rootScope objectScope BroadcastingSummary103104106110110113Creating modulesThe UI moduleThe search moduleThe parking application moduleRecommended modulesSummary115116118119120120[ iii ]

Table of ContentsChapter 7: Unit Testing121The Jasmine testing frameworkTesting AngularJS 24125126128129Creating the element with the directiveCompiling the directiveCalling the link function with the scopeInvoking the digest cycle130130130130Mocking with httpBackendRunning tests with Karma132140InstallationConfigurationRunning tests140141142Summary143Chapter 8: Automating the Workflow145Index159Automating the workflow with GruntInstallationConfigurationCreating a distribution packageExecuting the workflowManaging packages with BowerInstallationFinding packagesInstalling packagesUsing packagesCacheSummary[ iv ]145146146147155156156156157157158158

PrefaceFor more than 12 years, I have been developing all kinds of web applications,and along the way, I have had the opportunity to experience the vast majority offrameworks on the Java platform. In 2008, I moved from an architecture highly basedon backend web frameworks such as Struts and JSF to experience new challenges atthe frontend. I think the main goal was to stop creating those old-school andhard-to-use web applications, investing on interactivity and usability.At that time, I adopted the Google Web Toolkit, also known as GWT, building someweb applications for almost 2 years. The results were pretty amazing in terms of userexperience; however, I felt very upset about low productivity and also the amount ofcode that I had to write every day.After that, in 2010, I decided to change drastically, adopting a much simplerapproach by using just HTML, CSS, and JavaScript to write the frontend code. Theexperience was fantastic, which provided me with a very fast feedback cycle. Theonly problem was the lack of a layered architecture, which was unable to provide aclear separation of concerns while working with the JavaScript language. Also, I wasmissing things such as a strong dependency injection mechanism that would allowme to create reusable and testable components.While looking for a solution, a very experienced JavaScript developer and also agreat friend of mine, Rafael Nami, introduced me to AngularJS. In the followingweeks, I started to read everything about it and also writing some code. After afew weeks, I was thrilled because it had never been so easy to create amazing webapplications with so little code!

PrefaceOnly 2 months later, I launched my first web application based entirely onAngularJS, and honestly, I cannot imagine writing this same application usinganother kind of technology in this short period of time. I was so excited about it that Iwrote an article on using AngularJS with Spring MVC and Hibernate for a magazinecalled Java Magazine. After that, I created an AngularJS training program that alreadyhas more than 200 developers who enrolled last year.This book, AngularJS Essentials, is the result of that experience. This is a very practicalguide, filled with many step-by-step examples that will lead you through the bestpractices of this amazing framework.We are going to start, after a brief introduction, by learning how to create reusablecomponents with directives. Then, we will take a look at many data handlingtechniques, discovering a complete set of technologies that are capable to accomplishany challenge related to present, transform, and validate data on the user's interface.After that, we will explore the secrets of the dependency injection mechanismand also learn how to create services in order to improve the application's design.Also, we are going to discover the best way to deal with the scope and how tobreak up the application into separate modules, giving rise to reusable andinterchangeable libraries.Finally, we are going to learn how to test each component of the framework usingJasmine and also how to automate the workflow, creating an optimized distributionpackage with Grunt.Rodrigo BranasSoftware Architect, Author and International SpeakerAgile CodeWhat this book coversChapter 1, Getting Started with AngularJS, introduces the framework and itsarchitectural model. After that, we will start coding our first applicationand also understand how to organize our project.Chapter 2, Creating Reusable Components with Directives, explains how the directivesare one of the most important features of the framework. With them, we willunderstand how to extend the HTML language vocabulary, creating new behaviorsand reusable components.Chapter 3, Data Handling, explains how the framework provides a complete set oftechnologies to fulfill any requirement about presenting, transforming, synchronizing,and validating data on the user's interface. We will go through all of these technologiesin order to improve the user experience with our applications.[2]

PrefaceChapter 4, Dependency Injection and Services, explains how we are going to createreusable and decoupled components by implementing services and using thedependency injection mechanism.Chapter 5, Scope, discusses how scope is one of the main concepts of the framework.In this chapter, we will discover the best practices to deal with scope.Chapter 6, Modules, briefs us on how the framework is strongly based on the modules.In this chapter, we will understand how to break up our application into modules.Chapter 7, Unit Testing, shows how we will dive deeply into testing techniques. Weare going to understand how to test each framework component using Jasmine.Chapter 8, Automating the Workflow, discusses how we will create an optimizeddistribution package for our application using Grunt and its plugins. Also, we willdiscover how to manage our dependencies with Bower.What you need for this bookTo implement the code in this book, you will need to use your favorite developmentinterface and a web browser. I would recommend sublime text, but you may useAptana (which is based on Eclipse), WebStorm, or any other IDE.AngularJS is compatible with the most browsers such as Firefox, Chrome, Safari, andInternet Explorer. Feel free to choose the one you are used to.Who this book is forIf you have a passion for web development and are looking for a framework thatcould provide a reusable, maintainable, and modular way to create applications,and at the same time, help increase your productivity and satisfaction, this is thebook for you.ConventionsIn this book, you will find a number of styles of text that distinguish betweendifferent kinds of information. Here are some examples of these styles, and anexplanation of their meaning.Code words in text, database table names, folder names, filenames, file extensions,pathnames, dummy URLs, user input, and Twitter handles are shown as follows:"The http service wraps the low-level interaction with the XMLHttpRequest object,providing an easy way to perform AJAX calls without headaches."[3]

PrefaceA block of code is set as follows: http.get("/cars").success(function(data, status, headers, config) { scope.car data;}).error(function(data, status, headers, config) {console.log(data);});When we wish to draw your attention to a particular part of a code block, therelevant lines or items are set in bold: http.get("/cars").success(function(data, status, headers, config) { scope.car data;}).error(function(data, status, headers, config) {console.log(data);});Any command-line input or output is written as follows:bower install angularNew terms and important words are shown in bold. Words that you see on thescreen, in menus or dialog boxes for example, appear in the text like this: "Whathappens when we change the plate and click on the Show Plate button?".Warnings or important notes appear in a box like this.Tips and tricks appear like this.[4]

PrefaceReader feedbackFeedback from our readers is always welcome. Let us know what you think aboutthis book—what you liked or may have disliked. Reader feedback is important for usto develop titles that you really get the most out of.To send us general feedback, simply send an e-mail to feedback@packtpub.com,and mention the book title via the subject of your message.If there is a topic that you have expertise in and you are interested in either writingor contributing to a book, see our author guide on www.packtpub.com/authors.Customer supportNow that you are the proud owner of a Packt book, we have a number of things tohelp you to get the most from your purchase.Downloading the example codeYou can download the example code files for all Packt books you have purchasedfrom your account at http://www.packtpub.com. If you purchased this bookelsewhere, you can visit http://www.packtpub.com/support and register to havethe files e-mailed directly to you.ErrataAlthough we have taken every care to ensure the accuracy of our content, mistakesdo happen. If you find a mistake in one of our books—maybe a mistake in the text orthe code—we would be grateful if you would report this to us. By doing so, you cansave other readers from frustration and help us improve subsequent versions of thisbook. If you find any errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting your book, clicking on the errata submission form link,and entering the details of your errata. Once your errata are verified, your submissionwill be accepted and the errata will be uploaded on our website, or added to any list ofexisting errata, under the Errata section of that title. Any existing errata can be viewedby selecting your title from http://www.packtpub.com/support.[5]

PrefacePiracyPiracy of copyright material on the Internet is an ongoing problem across all media.At Packt, we take the protection of our copyright and licenses very seriously. If youcome across any illegal copies of our works, in any form, on the Internet, pleaseprovide us with the location address or website name immediately so that we canpursue a remedy.Please contact us at copyright@packtpub.com with a link to the suspectedpirated material.We appreciate your help in protecting our authors, and our ability to bringyou valuable content.QuestionsYou can contact us at questions@packtpub.com if you are having a problem withany aspect of the book, and we will do our best to address it.[6]

Getting Started withAngularJSHyperText Markup Language (HTML) was created in 1990 by Tim Berners-Lee—afamous physics and computer scientist—while he was working at CERN, theEuropean Organization for Nuclear Research. He was motivated about discoveringa better solution to share information among the researchers of the institution. Tosupport that, he also created the HyperText Transfer Protocol (HTTP) and its firstserver, giving rise to the World Wide Web (WWW).In the beginning, HTML was used just to create static documents with hyperlinks,allowing the navigation between them. However, in 1993, with the creation ofCommon Gateway Interface (CGI), it became possible to exhibit dynamic contentgenerated by server-side applications. One of the first languages used for thispurpose was Perl, followed by other languages such as Java, PHP, Ruby, an

AngularJS, and honestly, I cannot imagine writing this same application using another kind of technology in this short period of time. I was so excited about it that I wrote an article on using AngularJS with Spring MVC and Hibernate for a magazine called Java Magazine. After that, I created an AngularJS training program that already has more than 200 developers who enrolled last year. This .

Related Documents:

AngularJS uses dependency injection and make use of separation of concerns. AngularJS provides reusable components. AngularJS viii With AngularJS, the developers can achieve more functionality with short code. In AngularJS, views are pure html pages, and controllers written in JavaScript do the business processing. On the top of everything, AngularJS applications can run on all major browsers .

AngularJS Tutorial W3SCHOOLS.com AngularJS extends HTML with new attributes. AngularJS is perfect for Single Page Applications (SPAs). AngularJS is easy to learn. This Tutorial This tutorial is specially designed to help you learn AngularJS as quickly and efficiently as possible. First, you will learn the basics of AngularJS: directives, expressions, filters, modules, and controllers. Then you .

Beginning AngularJS Beginning AngularJS is your step-by-step guide to learning the powerful AngularJS JavaScript framework. AngularJS is one of the most respected and innovative frameworks for building properly structured, easy-to-develop web applications. This book will teach you the absolute essentials, from downloading and installing AngularJS, to using modules, controllers, expressions .

AngularJS provides data binding capability to HTML thus giving user a rich and responsive experience AngularJS code is unit testable. AngularJS uses dependency injection and make use of separation of concerns. AngularJS provides reusable components. With AngularJS,

AngularJS Tutorial, AngularJS Example pdf, AngularJS, AngularJS Example, angular ajax example, angular filter example, angular controller Created Date 11/29/2015 3:37:05 AM

AngularJS team at Google as an external contractor and is a founder member of the AngularUI project. He has spoken about AngularJS at Devoxx UK and numerous London meetups. He also runs training courses in AngularJS. His consultancy practice is now primarily focused on helping businesses make best use of AngularJS. I would like to thank the team at Google for giving us AngularJS, in particular .

Code Explanation for ng-transclude Directive in AngularJS: 1. The ng-app specifies the root element ( myApp ) to define AngularJS . ng-transclude directive is used to include the existing content "AngularJS" . Sample Output for ng-transclude Directive in AngularJS: 1. The content welcome to wikitechy is displayed in the output using the .

uplifting tank and the plastic deformation of the bottom plate at the shell-to-bottom juncture in the event of earthquake, the design spectrum for sloshing in tanks, the design pressure for silos, and the design methods for the under-ground storage tanks as well. The body of the recommendation was completely translated into English but the translation of the commentary was limited to the .