Tuesday, March 19, 2024

Ten Ways to Use Angular JS

To give you, the reader, top-quality content, I’ve been reaching out to industry leaders for their assistance. As a result, you are able to learn from many different perspectives. This article comes to you courtesy of Cameron Wilby of Origin Code Academy.

Tips for Working with Angular JS and JavaScript

Below, you will find ten tips that Cameron recommends when working with Angular JS and JavaScript.

Write Singularly Responsible Angular Components

Follow the Rule of one principle, which states you should define one component per file, recommended to be less than 400 lines of code. One component per file makes your code easier to read, maintain and avoid collisions with teams using a source control solution like Git or Mercurial. It also helps to avoid hidden bugs that often arise when combining components in a file where they may share variables, create unwanted closures, or unwanted coupling with dependencies.

image

Use Consistent Naming Conventions for Angular Components

Use consistent names for all components following a pattern that describes the component’s feature and, (optionally) its type. A recommended pattern for you to follow is feature.type.js. There are two names for most assets:

  • The filename (checkout.controller.js)
  • The registered component name with Angular (CheckoutController)

There’s an ongoing joke in the industry that there are only two hard things in software development; cache invalidation, and naming things. Naming conventions provide a consistent way to find the content at a glance. Consistency goes a long way to help your project, team, and the company provides tremendous efficiency.

Read: A Guide to Variable Scoping Angular.

Wrap Angular Components in an IIFE

Now that we’ve talked about keeping Angular components in separate files, let’s talk about how those files should be laid out. Wrap the entire file in an IFFE (Immediately Invoked Function Expression). This ensures that variable and function declarations do not live longer than expected in the global scope, which helps avoid naming collisions with other libraries. It also allows you to utilize the “use strict” declaration without affecting 3rd-party components that may not utilize “use strict”.

image2

Keep Data Calls in a Factory, Not in the Controller

You should keep logic for making data operations and interacting with data in a data service, contained in an Angular factory rather than in an Angular controller. Make data services responsible for XHR calls, local storage, stashing in memory, or any other data operation you can think of, and inject those into your Angular controller.

The controller’s responsibility is for the presentation and gathering of information to/from your HTML. It should not care how it gets the data, just that it knows who to ask for it. This will simplify the code in your controllers, and make it easier to unit test your controllers by being able to pass in a mock data service, which is easier than mocking the $http service.

image3

Write Minification-safe Angular Components

Minification is the act of compressing client code delivered by a server so that the file size is smaller. If you have a lot of user load on your web application, this will help your server handle more requests with fewer resources. For Angular code to be correctly minified, avoid using the shortcut syntax of declaring dependencies without using a minification-safe approach like this:

image4

Instead, you should manually identify dependencies using $inject. This is the easiest way to manually declare dependencies for an Angular component.

image5

Stop Using $scope, use the Controller-as Syntax

Controllers are constructed or “instantiated” when they are needed, and destructed or “deinstantiated” when they are no longer needed. The Controller-As syntax is closer to that of a JavaScript constructor than the classic method of injecting a redundant $scope service into your controller. It also promotes the use of binding to a “dotted” object in the View, which brings a greater sense of context, is easier to read, and avoids any and all scope inheritance issues that you may encounter in the future.

image6

image7

Read: How to Optimize Your Angular Applications.

Modularize Your Angular Code

Modular applications make it easy to plug-and-go since they allow development teams to build vertical slices of the applications and roll them out incrementally. This means we can plug in new features as we develop them. Here are some tips for creating modular Angular code:

  • Create small modules that encapsulate one responsibility. Create modules that represent feature areas, such as layout, reusable and shared services, dashboards s and app-specific features. e.g. customers, admin, sales.
  • Create modules that represent reusable application blocks for common services such as exception handling, logging, diagnostics, security, and local data stashing.
  • Create an application root module whose role is to pull together all of the modules and features of your application.

image8 

Use the Client-side Routing Framework Angular-ui-router

Client-side routing is important for single-page applications when creating a navigation flow between views and composing views that are made of many smaller templates and directives. UI Router offers all the features of the Angular router plus a few additional ones including nested routing and states. If you’ve been using the Angular router, you should find the syntax is similar and easy to migrate.

Keep Your Angular Application Organized

John Papa encourages keeping your application organized using the LIFT principle, which consists of 4 basic guidelines.

You should structure your app such that you can Locate your code quickly, Identify the code at a glance, keep the Flattest structure you can, and Try to stay DRY (Don’t Repeat Yourself).

  • Locate: If your team cannot find the files they need to work on quickly, they will not be able to work efficiently–meaning your structure needs to change.
  • Identify: When you look at a file, you should instantly know what it contains and represents.
  • Flat: Keep a flat folder structure as long as possible. When your folder structure is seven layers deep, it becomes difficult to work on a project. Think about menus on a website, anything deeper than two should merit serious consideration.
  • T-DRY (Try to stay DRY): Being DRY, or not creating files that have the same name is important, but not crucial if it sacrifices the other LIFT principles. If you have many grid views in your application, prefix your templates with the name of the area of the application that the template is a part of.

Automate the Writing of Quality Angular Code

Writing good Angular code does not mean having to write good Angular code all of the time. The process is simplified by following a style guide that provides snippets you can use in your favorite text editor and using a project generation framework such as Yeoman and the HotTowel template provided by John Papa in his Angular 1 style guide on his GitHub profile.

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Popular Articles

Featured