AngularJS Tricks

AngularJS CAN BE Fast!

  1. AngularJS Developers quickly discover that their med-large apps are buckling under the weight of scattered $watch's and the often bloated crutch known as $scope.
  2. Keep your $scope free of excess UI state, try limit the size & depth of your overall hierarchy.

2-way data binding: 2-way Sword

2-way binding alone makes coming from other frameworks like Backbone, well, frickin amazeballs.

The problem is: many sites chronically overuse Angular’s design patterns. This leads to directive sprawl and a $scope/rootScope which easily has 1000’s of instances, and can cling to huge objects preventing any hope of effective garbage collection.

You know where this is going: an exhausted browser! Forever doomed to work at a frantic pace executing endless and redundant UI/DOM re-compiles.

Stop OVER-Angular.JSification

“If your only tool is a hammer, then every problem looks like a nail.”

  • old adage

Does your app have a problem with directives?

current-user-status-label
  div(ng-if='loggedIn')
    view-user-surplusage(ng-if='!editMode')
      .head: contact-details(user='user')
      .tool: contact-buttons(loggedIn='loggedIn')
      a.edit-icon(ng-click='editMode = true')
    edit-user-surplusage(ng-if='editMode')
      .head: avatar-edit(user='user')
      .body: edit-contact-details(user='user')
      a.save-icon(ng-click='editMode = false')

Let’s design a flexible user-widget which helps:

  1. Versatile componentization w/ DRY Angular code
  2. Understandable directives, with minimal directive size/depth (mind your ng-repeats)
  3. Simple Service Layer
  4. Little actual coding to implement - just HTML/View Code
// jade
user-widget
  div(ng-if='loggedIn')
    div.edit(ng-if='editMode')
      h4.email-icon: input(type='email', ng-model='user.email')
      h4.phone-icon: input(type='email', ng-model='user.phone')
      a.save-icon(ng-click='editMode = false')
    div.show(ng-if='!editMode')
      h1.users-icon 
      h4.email-icon 
      h4.phone-icon 
      a.edit-icon(ng-click='editMode = true')
  div(ng-if='!loggedIn')
    h5: i Welcome User
    a.btn(href='/login') Login

Solutions

Angular Tips

  1. Use 1-way binding ( e.g. { :: title } )
  2. Limit recursive nesting of directives
  3. And if you must nest directives, NEVER do so inside an ng-repeat - Performance will start to inversely mirror something like O(n^2)^3 ;) I. Use native JS/DOM code in a factory pattern to create basic DOM/UI fragments, examples: Modal msg box, status bar. Call UI factories from either directives or controllers.
  4. Bonus: Understand cost and triggers of browser render lifecycle: animation, composite rendering, reflows

Use Browserify to Organize Project

Not specifically for Angular per-se, but essential for simple dependency resolution.

Browserify makes JS projects managable with virtually no added code overhead (ok, a few 100 chars).

Just read this section of the Browserify Handbook.

Alternatives

ReactJS from Facebook

For views which need minimal description: If you have tons of small reusable UI components - ReactJS might be a better choice:

  • If your project…?:
    • Has a different philosophy to UI/DOM implementation than Angular
    • Already has some kind of ‘framework’ - You can use ReactJS alongside AngularJS, Ember, Backbone.
    • Handles frequent data model changes in it’s own code, you’ll benefit by avoiding the ADHD digest/loop pattern of Angular

Polymer Project from Google

Pure-er JS Approach

  • By the way, here’s where I try create framework agnostic code (+1 testability, +1 reuse)
    1. Use plain javascript class to load data (AJAX/JSONP/Embedded in page, et al.)
    2. Use mustache templating to create HTML strings (or DOM directly)
    3. Cache rendered content in localStorage if you can
    4. (Optional) Now add an event listener to re-render the content. I have standardized on the event name refresh.<class-name>
Docker === Love

Docker Can Do Everything!*

Improve your process for:

  1. Testing Dev Tools & Servers WITH VIRTUALLY ZERO risk of messing up dependencies on your PC
  2. Testing your software
  3. Makes you write more idempotent, modular code… (I’ll write how to actually realize this in a follow up)

There may seem like a huge volume of new stuff to learn, don’t let that stop you from getting started.

Notes

  • If you see a docker run command with either options -d or -it:
    • -it or -i -t will run the configured command interactively
    • -d will start the docker container as a ‘daemon’ aka background service.

EXAMPLES

nginx


	# Note: using host-based, shared folders
	#(shared folders are not possible with the VOLUME Dockerfile cmd)
	sudo docker run --name web01 -d -p 8181:80 \
		-v $(NGINX_DIR)/etc:/etc/nginx \
		-v $(NGINX_DIR)/log:/var/log/nginx \
		-v $(NGINX_DIR)/www:/var/www/html \
		nginx:latest

	# Local data, isolated within instance
	sudo docker run --name web01 -d -p 8181:80 nginx:latest

	# nodejs
	sudo docker run --name nodejs01 -d -p 3300:3300 -p 4433:4433 nodejs:latest

Credits: https://dockerfile.github.io/#/nginx Docker will make your life easier throughout the entire SDLC.

  • Pretty close
Security Notes: RegEx

Denial-of-Service Regex Vulnerability

One of the most common, and yet hard-to-spot vulnerabilities I encounter relate to regular expressions. Either poorly written or poorly implemented.

Warning Signs

  1. You have multiple capture groups
  2. Global matching
  3. Expression is used with un-checked user input

Mitigation / Resolution

  1. RegEx is hard
    1. For example, here is how the really smart folks at OWASP recommend handling IP validation: ^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$
    2. That’s longer than a tweet, for a 4-byte IP Address!!!
  2. Make sure user input isn’t unduly long, when I know input data is reliably less than 40 chars, I’ll make sure I prevent anything over 64 - otherwise, an attacker could overwhelm my system with a flood of 4Kb requests.
  3. This affects almost every language and platform .NET/Node/Python/PERL/Java

Reference

Regular Expression DoS and Node.js

Tag Cloud