At this year’s Devoxx, I loved the session titled “Help! My AngularJS code is horrible”!
Thierry Chatel (@ThierryChatel) outlined the best practices needed to keep AngularJS code clean and maintainable.
The first best practice is to write simple and maintainable code. Thierry advises against premature optimization. For instance, don’t hesitate to execute a function multiple times. It won’t cost more resources. Then, to have a data model suitable to the application, it is best to work on an actual model instead of just using the JSON returned by backend services.
To structure the application, Thierry advises to start with a functional organization.
For instance:
Then, subfolders are organized by type (controllers, services, etc.) To simplify tests, it is good to have: one JS file = one module.
For instance:
To better manage routes, Thierry advises to create one routes declaration file per module. To get a certain route, use: $route.current
A controller is used to initialize the scope. Try not to use it to process data and do a lot of business logic. A controller is the link between services and scope.
To have lightweight controllers, we can create local controllers to manage view sections: one controller per view section.
We can create controllers on repeated scopes:
<ul><br></br>
<li ng-repeat="item in list" ng-controller="ItemCtrl">...</li><br></br>
</ul><br></br>
For instance:
Bad:ng-class="{alert: quantity(row) >= 100}"
OK:ng-class="{alert: orderSrv.isAlert(row)}"
Services can save data and process it.
Organize your services by layer.
To handle errors and notifications, use this organization: - An interceptor $http
Service override $exceptionhandler
A service for errors
A service for server logging
A notification service
Use directives to create your own elements or to personalize HTML elements.
Try to leverage HTML instead of replacing it (like in JSF). For instance, you can add a directive to an existing HTML element. It personalized the HTML element. Then, DOM manipulation is rather easy.