This AngularJS styleguide, written by @john_papa, has been a fantastic resource for me while learning Angular:
Among the key takeaways in style that I found most important were the following:
- Wrap all angular components, factories, controllers, and directives in an Immediately Invoked Function Expression (IIFE). This is to prevent variables and functions polluting the global namespace.
- Use the ControllerAs syntax to get access to
thisfrom the controller instead of using
$scope. This is to avoid the “dot problem” in the views. It is also a good idea to assign this to a consistent variable such as VM to avoid
$injectto list all dependencies in an array for the component to prevent minification mangling, and huge function declarations including dependencies can be hard to read.
The whole document is a great read though and I really encourage you to read it if you are working on an Angular project.