I would like to share some good tips that I have learned along the way that can help you start your AngularJS application on the right track.
Tip #1 : Directory Structure
1. Classify Based on File Type
In the below AngularJS example, objects of the same nature are regrouped into a single file. This demonstrates poor code organization.
The controller and service files will become enormously large and difficult to handle in no time.
2. Classify Based on MVC Type
This works better for small projects but once you’ve reached more than 10 files per directory you start losing time again.
3. Classify Based on Features
Instead of keeping the files grouped by type, group files based on features: This directory structure makes it much easier to find all the files related to a particular feature in a single folder, which will speed up development. It doesn’t look good to keep files with .js files, but the time savings are more valuable.
Tip #2 : Directives
AngularJS is not a framework to write code that modifies the DOM. To accomplish this we can use Directives.
- Earlier libraries like jQuery were used for this.
- Angular JS provides built-in directives that can help us.
- We can create our own directives also.
Tip #3 : Scope
- Scope must be used only in Controllers. Scopes are just used to get the data that the template will show and write this data in an object of the scope.
- Scope must not be modified in the templates. Even if AngularJS allows us to modify the scope in the templates, it’s something that we probably shouldn’t do.
Tip #4 : Multiple Bootstrap Modal in the Same Page
Once I come across a situation where I have to show multiple bootstrap modals from a single page. Also when I click a button from the first modal, I have to show another modal. This didn’t work for some time. The HTML page content was enormously large. The situation was such that I have to move the contents of the second modal to another HTML page. But, I found a better solution for this, which worked fine.
Tip #5 : Ng-if Vs Ng-hide
- Once I have faced a situation where I have to print the contents inside a div. On such situations ng-if is better since ng-show/ng-hide contents will always be visible on the print screen.
While using ng-if, I also have encountered a scenario where the scope values of the underlying HTML elements were not accessible. We can use ng-show/ng-hide instead when such an issue occurs.