Giới thiệu sách AngularJS: Mastering Web Application Development with AngularJS

Mastering Web Application Development with AngularJS

Table of Contents
Preface 1
Chapter 1: Angular Zen 7

Meet AngularJS 8
Getting familiar with the framework 8
Finding your way in the project 8
The community 9
Online learning resources 9
Libraries and extensions 9
Tools 9
Batarang 10
Plunker and jsFiddle 10
IDE extensions and plugins 10
AngularJS crash course 10
Hello World – the AngularJS example 10
Two-way data binding 12
The MVC pattern in AngularJS 12
Bird's eye view 13
Scopes in depth 15
View 21
Modules and dependency injection 26
Modules in AngularJS 26
Collaborating objects 27
Registering services 29
Modules lifecycle 33
Modules depending on other modules 35
AngularJS and the rest of the world 38
jQuery and AngularJS 39
Apples and oranges 40
A sneak peek into the future 41
Summary 41

Chapter 2: Building and Testing 43
Introducing the sample application 44
Getting familiar with the problem domain 44
Technical stack 45
Persistence store 46
MongoLab 46
Server-side environment 47
Third-party JavaScript libraries 48
Bootstrap CSS 48
Build system 48
Build system principles 49
Automate everything 49
Fail fast, fail clean 49
Different workflows, different commands 50
Build scripts are code too 50
Tools 50
Grunt.js 51
Testing libraries and tools 51
Jasmine 51
Karma runner 52
Organizing fles and folders 52
Root folders 52
Inside the source folder 54
AngularJS specifc fles 54
Start simple 56
Inside the test folder 57
File-naming conventions 57
AngularJS modules and fles 57
One fle, one module 58
Inside a module 59
Different syntax for registering providers 59
Syntax for declaring the confgure and run blocks 61
Automated testing 62
Unit tests 63
Anatomy of a Jasmine test 64
Testing AngularJS objects 65
Testing services 65
Testing controllers 67
Mock objects and asynchronous code testing 68
End-to-end tests 70
Daily workflow 71
Karma runner tips and tricks 72
Executing a subset of tests 73
Debugging 73
Summary 74

Chapter 3: Communicating with a Back-end Server 75
Making XHR and JSONP requests with $http 75
Getting familiar with the data model and MongoLab URLs 76
$http APIs quick tour 76
The confguration object primer 77
Request data conversion 78
Dealing with HTTP responses 79
Response data conversion 79
Dealing with same-origin policy restrictions 79
Overcoming same-origin policy restrictions with JSONP 80
JSONP limitations 81
Overcoming same-origin policy restrictions with CORS 81
Server-side proxies 83
The promise API with $q 84
Working with promises and the $q service 85
Learning $q service basics 85
Promises are frst-class JavaScript objects 87
Aggregating callbacks 88
Registering callbacks and the promise lifecycle 88
Asynchronous action chaining 89
More on $q 91
$q integration in AngularJS 93
The promise API with $http 94
Communicating with RESTful endpoints 95
The $resource service 95
Constructor-level and instance-level methods 97
$resource creates asynchronous methods 100
Limitations of the $resource service 101
Custom REST adapters with $http 101
Using advanced features of $http 104
Intercepting responses 104
Testing code that interacts with $http 106
Summary 108

Chapter 4: Displaying and Formatting Data 109
Referencing directives 109
Displaying results of expression evaluation 110
The interpolation directive 110
Rendering model values with ngBind 111
HTML content in AngularJS expressions 111
Conditional display 112
Including blocks of content conditionally 114
Rendering collections with the ngRepeat directive 114
Getting familiar with the ngRepeat directive 115
Special variables 115
Iterating over an object's properties 116
ngRepeat patterns 117
Lists and details 117
Altering tables, rows, and classes 119
DOM event handlers 120
Working effectively with DOM-based templates 121
Living with verbose syntax 121
ngRepeat and multiple DOM elements 122
Elements and attributes that can't be modifed at runtime 123
Custom HTML elements and older versions of IE 124
Handling model transformations with flters 124
Working with built-in flters 125
Formatting flters 125
Array-transforming flters 125
Writing custom flters – a pagination example 131
Accessing flters from the JavaScript code 133
Filters dos and don'ts 134
Filters and DOM manipulation 135
Costly data transformations in flters 136
Unstable flters 136
Summary 138

Chapter 5: Creating Advanced Forms 139
Comparing traditional forms with AngularJS forms 139
Introducing the ngModel directive 141
Creating a User Information Form 142
Understanding the input directives 143
Adding the required validation 143
Using text-based inputs (text, textarea, e-mail, URL, number) 143
Using checkbox inputs 144
Using radio inputs 145
Using select inputs 145
Providing simple string options 145
Providing dynamic options with the ngOptions directive 146
Using empty options with the select directive 148
Understanding select and object equivalence 149
Selecting multiple options 150
Working with traditional HTML hidden input felds 150
Embedding values from the server 150
Submitting a traditional HTML form 151
Looking inside ngModel data binding 151
Understanding ngModelController 151
Transforming the value between the model and the view 152
Tracking whether the value has changed 152
Tracking input feld validity 153
Validating AngularJS forms 153
Understanding ngFormController 153
Using the name attribute to attach forms to the scope 154
Adding dynamic behavior to the User Information Form 154
Showing validation errors 155
Disabling the save button 156
Disabling native browser validation 157
Nesting forms in other forms 157
Using subforms as reusable components 157
Repeating subforms 158
Validating repeated inputs 159
Handling traditional HTML form submission 161
Submitting forms directly to the server 161
Handling form submission events 161
Using ngSubmit to handle form submission 162
Using ngClick to handle form submission 162
Resetting the User Info form 162
Summary 164

Chapter 6: Organizing Navigation 165
URLs in single-page web applications 166
Hashbang URLs in the pre-HTML5 era 166
HTML5 and the history API 167
Using the $location service 168
Understanding the $location service API and URLs 169
Hashes, navigation within a page, and $anchorScroll 170
Confguring the HTML5 mode for URLs 171
Client side 171
Server side 171
Handcrafting navigation using the $location service 172
Structuring pages around routes 173
Mapping routes to URLs 174
Defning controllers in route partials 174
The missing bits in the handcrafted navigation 175
Using built-in AngularJS routing services 175
Basic routes defnition 175
Displaying the matched route's content 176
Matching flexible routes 177
Defning default routes 178
Accessing route parameter values 178
Reusing partials with different controllers 178
Avoiding UI flickering on route changes 179
Preventing route changes 181
Limitations of the $route service 182
One route corresponds to one rectangle on the screen 183
Handling multiple UI rectangles with ng-include 183
No nested routes support 184
Routing-specifc patterns, tips, and tricks 185
Handling links 185
Creating clickable links 186
Working with HTML5 and hashbang mode links consistently 186
Linking to external pages 187
Organizing route defnitions 187
Spreading route defnitions among several modules 188
Fighting code duplication in route defnitions 188
Summary 189

Chapter 7: Securing Your Application 191
Providing server-side authentication and authorization 192
Handling unauthorized access 192
Providing a server-side authentication API 192
Securing partial templates 193
Stopping malicious attacks 194
Preventing cookie snooping (man-in-the-middle attacks) 194
Preventing cross-site scripting attacks 195
Securing HTML content in AngularJS expressions 195
Allowing unsafe HTML bindings 196
Sanitizing HTML 196
Preventing the JSON injection vulnerability 197
Preventing cross-site request forgery 198
Adding client-side security support 198
Creating a security service 199
Showing a login form 200
Creating security-aware menus and toolbars 201
Hiding the menu items 201
Creating a login toolbar 202
Supporting authentication and authorization on the client 203
Handling authorization failures 203
Intercepting responses 204
HTTP response interceptors 204
Creating a securityInterceptor service 205
Creating the securityRetryQueue service 207
Notifying the security service 208
Preventing navigation to secure routes 208
Using route resolve functions 209
Creating the authorization service 210
Summary 212

Chapter 8: Building Your Own Directives 213
What are AngularJS directives? 214
Understanding the built-in directives 214
Using directives in the HTML markup 215
Following the directive compilation life-cycle 215
Writing unit tests for directives 217
Defning a directive 218
Styling buttons with directives 219
Writing a button directive 220
Understanding AngularJS widget directives 222
Writing a pagination directive 222
Writing tests for the pagination directive 223
Using an HTML template in a directive 224
Isolating our directive from its parent scope 225
Interpolating the attribute with @ 226
Binding data to the attribute with = 227
Providing a callback expression in the attribute with & 227
Implementing the widget 228
Adding a selectPage callback to the directive 229
Creating a custom validation directive 230
Requiring a directive controller 231
Making the controller optional 231
Searching for parents for the controller 232
Working with ngModelController 232
Writing custom validation directive tests 233
Implementing a custom validation directive 235
Creating an asynchronous model validator 235
Mocking up the Users service 236
Writing tests for asynchronous validation 237
Implementing the asynchronous validation directive 238
Wrapping the jQueryUI datepicker directive 239
Writing tests for directives that wrap libraries 240
Implementing the jQuery datepicker directive 242
Summary 243

Chapter 9: Building Advanced Directives 245
Using transclusion 245
Using transclusion in directives 245
Transcluding into an isolated scope directive 246
Creating an alert directive that uses transclusion 246
Understanding the replace property in the directive defnition 247
Understanding the transclude property in the directive defnition 248
Inserting the transcluded elements with ng-transclude 248
Understanding the scope of transclusion 248
Creating and working with transclusion functions 250
Creating a transclusion function with the $compile service 251
Cloning the original elements when transcluding 251
Accessing transclusion functions in directives 252
Getting the transclusion function in the compile function with transcludeFn 252
Getting the transclusion function in the directive controller with $transclude 253
Creating an if directive that uses transclusion 253
Using the priority property in a directive 255
Understanding directive controllers 256
Injecting special dependencies into directive controllers 257
Creating a controller-based pagination directive 258
Understanding the difference between directive
controllers and link functions 258
Injecting dependencies 259
The compilation process 259
Accessing other controllers 260
Accessing the transclusion function 261
Creating an accordion directive suite 261
Using a directive controller in accordion 262
Implementing the accordion directive 263
Implementing the accordion-group directive 263
Taking control of the compilation process 265
Creating a feld directive 265
Using the terminal property in directives 267
Using the $interpolate service 268
Binding to validation messages 269
Loading templates dynamically 269
Setting up the feld template 270
Summary 271

Chapter 10: Building AngularJS Web Applications
for an International Audience 273
Using locale-specifc symbols and settings 274
Confguring locale-specifc modules 274
Making use of available locale settings 275
Locale-specifc settings and AngularJS flters 275
Handling translations 276
Handling translated strings used in AngularJS templates 277
Using flters 278
Using directives 279
Handling translated strings used in the JavaScript code 280
Patterns, tips, and tricks 282
Initializing applications for a given locale 282
Consequences of including locales as part of URLs 283
Switching locales 284
Custom formatting for dates, numbers, and currencies 285
Summary 287

Chapter 11: Writing Robust AngularJS Web Applications 289
Understanding the inner workings of AngularJS 290
It is not a string-based template engine 290
Updating models in response to DOM events 291
Propagating model changes to the DOM 291
Synchronizing DOM and model 292
Scope.$apply – a key to the AngularJS world 293
Putting it all together 300
Performance tuning – set expectations, measure, tune, and repeat 301
Performance tuning of AngularJS applications 303
Optimizing CPU utilization 303
Speeding up $digest loops 303
Entering the $digest loop less frequently 310
Limit the number of turns per $digest loop 312
Optimizing memory consumption 312
Avoid deep-watching whenever possible 312
Consider the size of expressions being watched 314
The ng-repeat directive 314
Collection watching in ng-repeat 314
Many bindings made easy 315
Summary 315

Chapter 12: Packaging and Deploying AngularJS
Web Applications 317
Improving network-related performance 318
Minifying static resources 318
How does AngularJS infer dependencies? 318
Writing minifcation-safe JavaScript code 319
The pitfalls of array-style DI annotations 322
Preloading templates 323
Using the <script> directive to preload templates 324
Filling in the $templateCache service 325
Combining different preloading techniques 327
Optimizing the landing page 327
Avoid displaying templates in their unprocessed form 328
Hiding portions of the DOM with ng-cloak 328
Hiding individual expressions with ng-bind 329
Including AngularJS and application scripts 330
Referencing scripts 330
AngularJS and Asynchronous Module Defnition 331
Supported browsers 333
Working with Internet Explorer 333
Summary 334
Index 33