Wednesday, 20 February 2013

Developer Diary - AngularJS: Best Practices

Recently I have been exploring AngularJS as our new "weapon of choice" for UI development at work. Learning it can be difficult as the documentation is a bit dense. However I have found some awesome videos given by the makers on YouTube!

In these series of posts I will be giving my take on the videos and I welcome any feedback!

Summary of key points I found in this video on Best Practices:

Application Structure

  • Use a standard, it helps!
  • Google recommend Yeoman
    • This looks absolutely awesome but it doesn't work in Windows atm :(

Script Loading

  • Asynchronous loaders cannot use ng-app attribute to initialise your application
  • Require.js comes recommended for dependency management


  • When changing the model outside of Angular, use $apply function so Angular is notified and updates the UI


  • Minification may have limited benefit in Angular because files should already be small (in theory).
    • However minification may help, you need to measure and test this yourself.
  • Similarly concatenation may have limited benefit (again measure and test across multiple browsers).
  • Ensure the server is "gzip" enabled
  • index.html file should be non-cacheable
  • Cache by these by version (I don't really understand this...):
    • views
    • code
    • images
    • css

Separation of Concerns

  • Controllers should focus on:
    • what HAPPENS when a user does something
    • where to GET data from
  • Services should be:
    • Singleton
      • allowing for caching of data which is not destroyed between navigation
    • Hold logic required in multiple locations


  • Views should treat scope as read-only
  • Controllers should treat scope as write-only
  • Scope != Model, scope just references your model.


  • For optimum performance, ensure $watch getter function is:
    • Fast
    • Idempotent
    • Does not contain mutating logic
  • The number of bindings per page also heavily affects the performance.
  • Doing ng-hide doesn't actually remove the hidden component
    • This can lead to slow performance.
    • Use ng-include and ng-view instead
  • Avoid having >100 items in a repeater
    • The performance may suffer
    • Also UX may suffer, humans aren't good at taking in that much information at once.
  • Filters can be expensive
    • Recommended that an "intermediate model" is used instead.


  • These maybe simplified in Angular 2.0
  • For IE compatibility, the best form of directive to use is attribute.

Other Points

  • {{ }} should be avoided on the index.html because it can cause "screen flash" as the binding is updated after angular is loaded
    • ng-bind should be used instead
  • Angular 2.0 has some potentially interesting features:
    • Simplification of directives
    • Animations built in
    • Server-side pre-rendering of views

No comments:

Post a Comment