AngularJS provides MVC architecture for developing SPA (Single Page Application). Key features are two-way data binding, built-in dependency injection, templates written with HTML and facilities for unit testing of every component in the application.
AngularJS $scope objects
You can easily build a big mess with the data you write into and read from scopes. Keep scopes under control:
- Use “Controller as” syntax.
- Store a model object in your scopes, instead of storing your data directly.
- Ensure you always use a dot when accessing your data – “Controller as” syntax will help you with this.
Two-way data binding
Two-way data binding in AngularJS is a cool feature. Changes in model are propagated to be viewed automatically and changes in view are propagated to models automatically too.
AngularJS performs dirty-checking of values to fire change events, versus change listeners of other frameworks. That means checking if any variable in scopes have changed, in cycles called digest cycles.
In order to improve your application performance:
- Avoid using complex AngularJS expressions. AngularJS expressions can be evaluated a huge number of times. Use one-time binding expressions when possible.
- Use $watchCollection over $watch with a true third parameter to observe objects and arrays.
- Avoid ng-repeat where possible.
AngularJS directives are great. They allow you to extend HTML. You can create reusable DOM elements that will be shared across your application. When working on an AngularJS application:
- Do not manipulate or access DOM in controllers. Never do it. Use directives for DOM manipulation.
- Directives can be used as element names, attributes, class names and comments. Restrict your directives to element names and attributes, it will make easier finding out matching between directives and DOM elements.
Besides that, you should take care of keeping up with latest releases of AngularJS. Handy features are introduced continuously. To make your upgrading easier:
- Avoid obsolete directive formats. Use ng-xyz or data-ng-xyz formats, others are supported just for legacy reasons and could not be supported in future releases.
- Replace $http deprecated functions, success and error, by then function.
- Do not access scope properties starting by $$, the AngularJS naming convention states that they are private properties.
Last but not least, organize your code:
- Pay attention to your folder layout.
- Define just one AngularJS component per file.
- Use a consistent naming convention.
Stay tuned, soon you will have a set of new specific rules for AngularJS applications available in Kiuwan Code Analysis These rules will help you to follow best practices and enjoy building great AngularJS applications.