This article lists some of the best practices that would be useful for developers while they are coding with AngularJS.
Here are some good practices for AngularJS applications separated into five categories:
When we start to build an AngularJS application sometimes we don’t know exactly how to organise our files or even know what files we need. For this, the AngularJS team recommends two solutions:
- Use the angular-seed (https://github.com/angular/angular-seed) project, which is basically a skeleton of a typical AngularJS application. You just need to clone the repository.
The users can easily add AngularJS to a web page with the
<script> tag. But often the framework and related scripts impact the loading of HTML code. The developers can easily improve the page load time by placing the entire
<script> tag at the bottom of the page. When AngularJS and related scripts are placed at the bottom of the page, the HTML code can be loaded without any interruption and delay.
While using AngularJS, the developers can inject dependencies in a number of ways. For instance, they can perform dependency injection using the new operator or create a service registry for the dependency. Likewise, they can keep the dependency injection global and store it in a single place. But the developers can always consider passing the dependency to the constructor function instead of using any other option. When the dependency is passed to the constructor function, the dependency object will be generated by other functions or objects without any manual intervention.
Regarding the object scope that we have in AngularJS, we have three simple rules:
- The scope must be write-only in the controllers, meaning that the controller is in charge of using another component, like a service, to get the data that the template will show and write this data in an object of the scope.
- The scope must be read-only in the templates, meaning that even if AngularJS allows us to write code that modifies the scope in the templates, it’s something that we must be very cautious about and probably shouldn’t do.
AngularJS allows developers to organize and control the application through individual modules. Each module contains certain components of the website. But the developers have the option to create modules without any restriction. Hence, many developers prefer creating individual modules for components like services, directives, and controllers. There are always chances that a specific functionality of the web application will require components and dependencies from different modules. So the developers must make it a practice to include related services, directives, controllers and dependencies in the same module to structure the application more flexible.
- One may want to use Jasmine/Karma combination for doing controller methods testing.
- Protractor framework can be used for E2E testing, as recommended. Read more on the Angular page for E2E testing.