AngularJS – best practices for the MV* pattern usage


During experimentation with AngularJS and using my previous experience with MV* set of patterns and their implementation I found out some interesting facts that may help you a lot in the future development of a loosely coupled web front-end.

[sdropcap]1.[/sdropcap] The KISS principle still applies – please do your self a favour and don’t try to reinvent the wheel. And, as one of my dear Javascript expert and friend would says, don’t create unicorns. Just play nice from the start and you’ll be able to reuse the code without huge modifications upon AngularJS framework updates. And no, a megagon is still not a circle!

[sdropcap]2.[/sdropcap] Since you don’t have a specific templating engine, your HTML is your view. Don’t put more Javascript logic there, try to use for animations and effects the CSS 3 Transitions – they are quite powerful! Use AngularJS’s Directives – they will help you separate the reusable parts of your app and your application will be DRY and easy to mantain. Who doesn’t hate the Friday afternoon bugs which seem to take an eternity to fix?

[sdropcap]3.[/sdropcap] Make your Controller independent of the view – do you want testability also, isn’t it? No interaction should be allowed from the controller to the view, it should only supply the ViewModel on which the View will render the data. In case of the need for custom interactions or reusability, READ AGAIN No. 2! Make CSS3 transitions your friend, it will provide fluent effects also on the less powerful mobile devices. Javascript is a VM and jQuery sits on top of it, so using CSS3 you’ll use the browser’S capabilites, not relying on the 2 extra layers on top of it. Plus that you give more processing power to AngularJS!

As a recommended practice, the Directives should know and modify the View; the View must know about its controller and how to interact with it; the Controller should know and use Services. That’s it. Keep it clean and you’ll be on the safe side. No unicorns, ok?

[sdropcap]4.[/sdropcap] The controller should be build around the Single Responsibility principle. Should do one thing and one thing only. If you need extra interaction, just split it in two controllers – will improve your testing and your certainty that every execution path is proven to be correct using testing. 

[sdropcap]5.[/sdropcap] And please, set a naming convention and use it consistently! Whatever you like and suits your style, but be expressive when naming because you’ll spare a lot of debugging time later!

[ideabox]This article is based on my previous experience with MV* implementations- MVVM and MVC mainly:

  • Mobile: Silverlight for Windows Phone
  • Web: Ruby on Rails and ASP .Net MVC; Knockout, ExtJS, Kendo UI and AngularJS
  • WPF: Surface multi-touch multi user framework