Essential Tips and Tricks for AngularJS Developers

Essential Tips and Tricks for AngularJS Developers

AngularJS is an open-source JavaScript framework, maintained by Google, that assists with running single-page applications. Its goal is to augment browser-based applications with model–view–controller (MVC) capability, in an effort to make both development and testing easier. AngularJS lets you extend HTML vocabulary for your application.

At the onset, you may find AngularJS easy to start but a large part of the code hides behind the abstraction layer that even the experienced developers wouldn’t like to explore due to its sheer size and complexity. Hence, in this article we’ve brought up some of the best tips and tricks for AngularJS developers. Also, it’ll include best practices for writing AngularJS code and address a few of the debugging techniques as well.

1. Optimized Code Structure.

As someone rightfully said, “Without a solid foundation, you’ll have trouble creating anything of value.“. And as is the case with many of us who begin writing code to finish but don’t focus on the maintainability. Hence, you must plan for everything starting from the folder structure for your code. Here is a sample code structure for an AngularJS project that you may follow.

  • Create an “app” folder – the root of your project.
  • Place all your shared data in the “app/common” folder.
  • Put all your components files inside the “app/components” folder.
  • All of your resources should go inside the “assets” folder.

Recommended Code Structure.

app/
----- app.module.js
----- app.routes.js
----- common/ // re-usable components
---------- controllers
---------- directives
---------- services
---------- html
----- components/ // every component is a mini Angular app.
---------- home/
--------------- homeController.js
--------------- homeService.js
--------------- homeView.html
---------- cart/
--------------- cartController.js
--------------- cartService.js
--------------- cartView.html
assets/
----- img/ // media files for your app
----- css/ // styling files
----- js/ // script files written for your app
----- libs/ // third-party libraries e.g. jQuery, Underscore, etc.
index.html

2. Understand Scope In AngularJS

The scope is something which binds the HTML with the JavaScript. It’s an object created by AngularJS to access the methods and properties of the controllers and directives. It includes a lot of handy information which is quite useful for debugging purpose.

  • To access scope, first of all, you need to get to the target element. It is easily doable with the help of Chrome’s dev tools. Just inspect the web element and switch to the console tab.

  • There you can type $($0) or angular.element($0) to print the element. And then can use $($0).scope() to get to the scope object.

  • With the help of scope, you can know its whereabouts like its parents [$($0).scope().$parent] or parents of parents [$($0).scope().$parent.$parent] etc.

  • If the selected element is a directive having isolate scope, then use $($0).isolateScope() to determine its scope.

  • Also, using the $($0).scope().<Property Name> will return the value of that property.

  • If you wish to check if the scope includes a property or not, then use the $($0).scope().hasOwnProperty(‘<Property Name>’).

3. Restrain From Doing DOM Manipulation.

You should not carry out any DOM Manipulations inside controllers, services or anywhere else. However, you can have them working in the directives. Or the best is to avoid them as whenever there is any, else AngularJS will trigger events to maintain the application state. And It’ll lead to extra overhead for the application.

4. Use Service To Share Data Between Controllers.

Sometimes, you have two or more views in different routes that need access to some status variable. Or you may have multiple components which need access to the same piece of data.

In such cases, the best approach to share data between controllers is by creating a dedicated service for this. See the below example.

Let’s say we’ve two controllers dc1 and dc2. And exchange is the name of our data service.


var myApp = angular.module("myApp", ['beginexchange']);
 
myApp.controller("dc1", ['$scope', 'exchange',
    function ($scope, SharedDataService) {
    $scope.Product = SharedDataService;
 
    }]);
 
myApp.controller("dc2", ['$scope', 'exchange',
    function ($scope, SharedDataService) {
    $scope.Product = SharedDataService;
 
}]);

Now, you can implement the view using the controllers in the following fashion.

<div ng-controller="dc1">
            <h2>In Controller 1</h2>
            <input type="text" ng-model="Product.name" /> <br/>
            <input type="text" ng-model="Product.price" />
            <h3>Product {{Product.name}} costs {{Product.price}}  </h3>
</div>
<br/>
<div ng-controller="dc2">
            <h2>In Controller 2</h2>
            <h3>Product {{Product.name}} costs {{Product.price}}  </h3>
</div>

5. Don’t Use Controllers For Presentation Logic.

The recommended development model in AngularJS is the MVC. It consists of a model, view, and controller. When you add presentation code in the controller, then you are breaking the integrity of the layers. Also, it could lead to unmanageable code. And it would become hard for other developers to debug. So, if you require a change in any HTML element or any DOM manipulation, then you should do it in the presentation layer.

6. Use Track By For Quickly Displaying List Items.

You can control the frequency of rendering lists by using the Track By feature. Otherwise, displaying the list will require the DOM to reload for every item in the list.

See the below example.

<div ng-repeat="listitem in empList">
</div>

The above approach will make your code less efficient. Hence, you should be using the following code.

<div ng-repeat=" listitem in empList track by item.empid">
</div>

The code above still follows the same process. But it would display the list faster and make the application more efficient. As it is using the unique key instead of using a random one.

7. Adapt ControllerAs Approach.

In spite of using the scope as a container, it’s better to use a controller as itself.

For your information, in controllers, it is no longer suggested to use the “$scope” variable. But we can assign everything to a controller object like this.text=” “. And in HTML templates, we should just set a name for our controller variable.

ng-controller=”MasterCtrl as ctrl"


It would work without any issue. However, there could be people who may oppose this approach but I think it is useful for developers who faced problems in following the scope based approach.

You can use the controllerAs property inside the directive signature.

app.directive('Directive', function () {
    return {
      restrict: 'EA',
      templateUrl: 'temp.html',
      scope: true,
      controller: function () {},
      controllerAs: 'vm'
    }
});

Or also use it for controllers via $routeProvider in the following manner.

app.config(function ($routeProvider) {
  $routeProvider
  .when('/', {
    templateUrl: 'hero.html',
    controllerAs: 'hero',
    controller: 'HeroCtrl'
  })
});


8. Integrate Less To Produce CSS.

LESS, which is a CSS pre-processor and provides features like mixins, operators, and functions. Many developers recommend the use of Less for web development with AngularJS. While working with it, there are a lot of things which you can achieve.

  • It offers high-level styling syntax to allow web developers to produce advanced CSS.

  • LESS preprocessor compiles into standard CSS before the browser begins rendering a web page.

  • Pre-compiled CSS files can be easily transferred to a production web server.

9. Use Built-In Validations In AngularJS.

AngularJS embeds an excellent feature of auto-validating your form. And eventually, this ability can become the backbone of any application that receives user inputs.

Usually, the validation of a form goes through a chain of code blocks. They include multiple “if, else if…” which leads to undesired complexity. In this approach, the user has to submit the form a no. of times to handle one validation error after the other.

However, AngularJS brings a different way of form validation which happens as the user fills it out. And all of these validations are inherent in Angular JS in the form of directives.

10. Avoid Filters With Large Arrays.

Filters run on each digest loop and create a new array every time they execute. In such cases, prefer to watch your list and do filtering upon detecting a change.

See this example of a bad use of filters in a digest loop.

<li ng-repeat="item in heroList | myHeroSortFilter"></li>


Whereas, now see a good example.

In Controller.

$scope.filteredItems = $scope.items;
$scope.$watchCollection('items', function () {
    // Apply filter on change detection
    $scope.filteredItems = myHeroFilter($scope.items);
});

In HTML.


<li ng-repeat="item in heroList"></li>


11. How To Detect If Property Changes.

Here is the sample code that monitors a property. It’ll print logs on the console.

var hero = {a: 2};

var _prop = obj.prop;

Object.defineProperty(prop, 'prop', {
 get: function () { return _prop; },
 set: function (val) { _prop = val; console.log('Property changed.'); }
});

12. How To Detect If An Item Changes In A List.

There could be two ways to achieve it. First of all, let’s see the bad example. The downside is, it’ll create copies of the object with each comparison.


$scope.watch('empList',
    function watchListener() {
        // Print a message if the reporting of any employee changes.
    }
}, true);

Now, let’s see the approach that you should use.


$scope.watchCollection('empList',
    function watchListener() {
        // Print a message if the reporting of any employee changes.
    }
});

13. Slow Down The Watchers From Being Called.

For delaying the execution of watchers, we can use the “debounce” property.


<input type="text" name="empName"
ng-model="emp.name"
ng-model-options="{ debounce: 100 }" /><br />

The above code will change model value only after waiting for 100 ms after the last change happened in input value.

14. Select An Element By ID Or Class.

For selecting the element using ID, use the following code.

angular.element(document.querySelector('#id'))


For selecting the element based on class name, use this code.

angular.element(elem.querySelector('.classname'))


15. Use Multiple Controllers In Separate Modules.

If you have multiple controllers in separate modules, then you can still use them inside a single module. However, you’ll need to include them as dependencies of your main module.


var dc1 = angular.module('dc1', []);
var dc2 = angular.module('dc2', []);
var app = angular.module('app', ['dc1', 'dc2']);

dc1.controller('dc1', function ($scope) {
    // Place your controller code here
});

dc2.controller('dc2', function ($scope) {
    // Place your controller code here
});

Conclusion

The above tips can be a good foundation for your future applications. These will help you improve skills and grow your knowledge in AngularJS. Also, you can improve productivity by turning your focus on the core business logic of your project.

Thanks for reading !

Migrating from AngularJS to Angular

Migrating from AngularJS to Angular

Migrating from AngularJS to Angular a hybrid system architecture running both AngularJS and Angular

Intro

Dealing with legacy code/technologies is never fun and the path to migration isn’t always as straight forward as you want. If you are a small startup, trying to balance business requirements, scarce resources and aggressive deadlines, it becomes even more complicated.

This is the situation one of the startups I was advising was facing.

A bit of background

The startup was developing a SaaS for the last 2 years and (at the time) had around 15 clients worldwide. In these 2 years their code base grew pretty fast and lead to quite a lot of fast/reckless written code. There was nobody to be blame, this is pretty common in the startup world when business needs move way faster than you expect and you start sacrificing code qualify for quantity.

The system architecture was pretty simple. 
• a frontend application written in AngularJS (split into multiple modules that were selected at build time depending on the clients’ configuration)
• a backend application written in Python 2.7 and Django 1.9 using a Mysql database
• Celery for running async tasks

Each client would get their own isolated environment deployed on AWS:
• Apache in front of the Django application (deployed on multiple EC2 instances behind an ELB)
• AngularJS build deployed on individual S3 buckets with CloudFront in front of them

Path to migration

A few months before starting the migration, development was getting very slow, features were not coming out as fast, deadlines were missed and clients were reporting more issues with every update that we were rolling out. It was at this time that we started thinking more seriously about some kind of refactoring or major improvement.

We didn’t know exactly what we were going to “refactor/improve” so we started off by answering three questions (I recommend that anyone who is thinking about a migration/refactoring think really hard about the how to answer them):

1st question: Why is refactoring necessary now ?

This is a very important questions to answer because it helps you understand the value of the migration and also it helps to keep the team focused on the desired outcome. For example because i don’t like the way the code is written isn’t good enough reason. The reason has to have a clear value proposition that somehow directly or indirectly benefits the customers.

For us it was mainly three things:
 1. feature development was becoming painfully slow;
 2. code was unpredictable. we would work in one part of the application and break 3 other parts without realizing;
 3. single point of failure: only 1 engineer knew the FE code base completely and only he could develop new features on the codebase (this is out of a team of only 5 engineers)

So our goal was simple:

improve FE development velocity and remove the simple point of failure by empowering other engineers to develop FE features

2nd question: Who is going to do the migration ?

You can answer this question either now or after the 3rd question. Depending on the size of the company and on the available resources it can be one person, several people, an entire team, etc…

We were in a difficult situation. The only developer who could work on this couldn’t because he was busy building critical features for our customers. Luckily we had one senior backend engineer who wanted to get some FE exposure so he volunteered to take on the task. We also decided to time-box a proof of concept at 2 weeks. We did this because we didn’t know how long it would take to figure out a solution or whether the engineer could actually do this task since he hadn’t worked on FE before.

3rd question: What are we actually going to do ? The answer here usually involves some discovery time, a few tech proposals and a general overview of the options with the entire team while weighing the pros and cons of each.

For us one thing was clear from the start: we didn’t want to invest any resources into learning/on-boarding engineers on AngularJS. AngularJS had already entered Long Term Support and we didn’t want to have our engineers invest time in something that might not benefit them long term. This meant that refactoring the existing AngularJS code was not an option. So we started looking at Angular6 …

The migration

There a multiple approaches on how to have a hybrid app running different frameworks. After reviewing some options we decided that — for us — the best way to move forward was to simply have 2 separate FE applications deployed: the legacy AngularJS one and the new Angular one. This meant that any state on one app could not be transferred to the other application, which wasn’t such a big deal for us since only new modules were going to be developed using Angular and our modules didn’t share state with each other.

From the client’s perspective everything would look like one application, except for a page reload when they would move between the applications.

Pros to this approach

  • speed: get something up and running without untangling legacy code
  • safety: no risk of breaking the current live app since it would be a new code based deployed next to the old one (especially since a developer with no previous exposure to the project was working on it)
  • stop legacy development: we stop adding more code the an already unmanageable codebase

Cons to this approach:

  • maintaining legacy code: it didn’t address feature improvements on existing modules; old modules would still be in AngularJS for an undefined period of time
  • duplicating parts of the code: since the new app had to look and feel like the old one any themes, custom components would have to be written in both places. Also some parts of the layout would have to be duplicated in new app (like header, menu, etc.. ) and any changes to those components would have to be done in both apps

We already knew of a new module that we wanted to build so we started form scratch with a new Angular 6 project and we used this new module for our 2 weeks proof of concept.

Step 1— same domain

Have both apps running on the same domain so that they have access to the same cookies and local data. This was extremely important since only the AngularJS app would continue handing authentication & authorization.

Step 2— look and feel

Both apps The goal was to make the new app look the same as the original application. So we: 
 • copied over all the stylesheets
 • implemented the base layout of the application (header & menu drawer)

Step 3 — authentication & authorization

We had to duplicate the authorization logic in the Angular6 app and make sure the correct session tokens were available to allow access to the module

Step 4— routing between apps

Since our main navigation links would take you to either app, we decided do move all that logic to a backend service called menu-service. This would eliminate the need to write any navigation changes in both apps and also would allow for greater runtime control over what navigation buttons we show.

Example:

HEADER: Authorization: Bearer xxxxx
GET menu-service/v1/menu/?type=0|1 (0: legacy, 1: new)
[{
  "slug": "refresh",
  "name" : "Refresh",
  "icon" : "fa-refresh",
  "type" : 1  
 }, {
  "slug": "module1",
  "name" : "Module1",
  "icon" : "fa-module1",
  "type" : 1
}, {
  "slug": "module2",
  "name" : "Module2",
  "icon" : "fa-module2",
  "type" : 0
}, {
  "slug": "logout",
  "name" : "Logout",
  "icon" : "fa-logout",
  "type" : 0
}]

In the above example based on the type value we identify that the module1 and refresh are links towards the new application while module2 and logout are links in the old application.
This information allows each application to decide whether to use the internal routing mechanism or do a window.location redirect

Example of routing in the Angular app (AngularJS does something similar):

export class MenuService {
  constructor(private router: Router) {  }
  onMenuItemClicked(menuItem): void {
    if (menuItem.type === 1) {
      this.router.navigate([menuItem.slug])    
    } else {   
      const url = `${legacy_endpoint}/${menuItem.slug}`;
      window.location.href = url      
    } 
  }
}

Step 5— building/deployment on a real environment

Like i mentioned in the beginning the AngularJS application was deployed to an AWS S3 bucket and exposed through Cloudfront to take advantage of the massively scaled and globally distributed infrastructure offered by AWS.

The result we wanted was the following: anything that has the url [https://hostname/v2](https://hostname/v2)/ is routed to the Angular application and everything else is routed to the legacy AngularJS app.

We used base-href and to make sure our Angular6 application builds accordingly

ng build --base-href /v2/ --deploy-url /v2/

Unfortunately we didn’t manage to achieve the desired routing behavior with AWS Cloudfront. This was a big disappointment since we had to pivot to a less optimal solution. (if anyone has any suggestion on how to do this in Cloudfront i’d love to hear it)

We ended up with the following structure:
• each app deployed in a NGINX Docker container

# AngularJS — Dockerfile:
FROM nginx:alpine
COPY dist /usr/share/nginx/html
--------------------------------------------------------------------
# Angular6 — Dockerfile:
FROM nginx:alpine
COPY dist /usr/share/nginx/html/v2

• AWS ALB with path routing

Step 6: Local development

Local development for the AngularJS application didn’t have to change. However in order to develop on the Angular6 app you had to also run the AngularJS application to be able to authenticate and get the appropriate session tokens.

We were already using Docker for deploying our application as containers. So we added a Makefile target to run the latest from our Docker repository

# Angular6 — Makefile:
AWS_REPOSITORY = xxx.dkr.ecr.eu-central-1.amazonaws.com
JS_APP_NAME = angular-js
...
run-local: 
  docker run -p 8080:80 $(AWS_REPOSITORY)/$(JS_APP_NAME):latest

Conclusion

This might not be the cleanest or optimal solution, however it was the fastest way towards our goals. And this was the most important thing to us.

The goal of this post isn’t to teach you how to do a AngularJS to Angular6 migration but instead is to showcase our path when dealing with such a task.

Further reading:

An in-depth look at Angular’s ng template

Angular 8 Data (Event & Property) Binding Tutorial: Build your First Angular App

Angular 8 Forms Tutorial - Reactive Forms Validation Example

What is the difference between JavaScript and AngularJS?

JavaScript is a client-side programming language used for creating dynamic websites and apps to run in the client's browser whereas AngularJS is a fully featured web app framework established on JavaScript and managed by Google.

JavaScript is a client-side programming language used for creating dynamic websites and apps to run in the client's browser whereas AngularJS is a fully featured web app framework established on JavaScript and managed by Google.


What’s the difference between AngularJS and Angular?

What’s the difference between AngularJS and Angular?

Angular vs Angularjs - key differences, performance, and popularity

AngularJS was released in 2009 and quickly became popular for it's two-way data binding, MVC architecture, and code reusability.

When alternatives like React and Vue delivered the same advantages of AngularJS with better performance, the Angular team decided to completely rewrite the framework.

Each subsequent release of Angular (4,5,6,7,8) has been mostly non-breaking incremental changes. For these reasons, "Angular" now refers to Angular 2+ and "AngularJS" the original.

Key Differences

Here are the key differences between Angular 2+ and AngularJS:

TypeScript

Angular was rewritten using TypeScript. TypeScript is a superset of JavaScript. It compiles to regular vanilla JavaScript but provides syntax for type checking, annotations, and ES6 based extensions.

Since TypeScript is a superset of JavaScript, it needs to be compiled or "transpiled" into ES5 JavaScript so your code still runs in the browser. This requires the use of NodeJS and other build tools for preprocessing TypeScript files.

While using Angular 2+ without TypeScript is possible, the industry standard is to adopt TypeScript as it plays much better with the Angular ecosystem.

MVC vs Component Architecture

AngularJS adheres to the model, view, controller (MVC) software design pattern. Controllers are defined with $scope variables representing an underlying data model. This data model can be updated in both the view and the controller. The view is an HTML file which both displays and dynamically updates $scope variables.

Angular 2+ utilizes more of a component based architecture. Isolated pieces of functionality are defined in components. These components reference their own templates and stylesheets and exist in a hierarchy of other components.

Dependency Injection (DI)

Both AngularJS and Angular use dependency injection. DI allows you to share commonly used functionality across different controllers or components.

In AngularJS, dependencies are injected in controller functions, link functions, and directive definitions.

In Angular, constructor functions, providers, and declarations are used to manage these dependencies.

Angular CLI

Angular 2+ features the Angular CLI: a command line interface for quickly generating Angular components, services, directives, etc. It comes with convenient commands for building your Angular project (compiling TypeScript files and other assets into vanilla js files that run in the browser). It also makes building your project for different environments easier and allows for things like linting, type checking, etc.

AngularJS doesn't have it's own CLI.

Performance

Angular is much faster than AngularJS. In fact, it's said that Angular can be more than 5X faster based on the design of your application.

Popularity

Before the advent of React and Vue, AngularJS was very popular. It offered an elegant solution to the JavaScript SPA with two-way data binding and MVC architecture.

Being able to dynamically update a JavaScript POJO from an HTML template caused a lot of buzz. As a result, alternatives like React and Vue emerged with superior diffing algorithms that left AngularJS in the dust.

Angular fought back with the release of Angular 2 (2016). Today, Angular remains one of the most popular frameworks for UI development.

While AngularJS is still used today, it's popularity has died in favor of more current options like Angular 2+, React, and Vue.

Performance

The problem with AngularJS

Performance is one of the biggest problems with the original AngularJS. This is due to the underlying "magic" behind what originally made AngularJS so popular.

To achieve two-way data binding, AngularJS relies on a digest cycle to keep views in sync with their underlying data models. It works by augmenting all event handlers (clicks, ajax, timeouts) with a process called "dirty checking". Each scoped variable is compared to it's previous value.

If something has changed, the watchers and templates are updated with the new value and the process runs again to see if anything else has changed. In this way, the view is constantly in sync with the data model.

The problem with the AngularJS digest cycle is it's unpredictable. As applications grow, the "checking" process becomes more intensive and can run infinitely with two way data flow.

Angular 2+ to the rescue

To address these issues, the Angular team rewrote the framework with flux architecture in mind. Specifically unidirectional data flow was fundamental to reengineering change detection in Angular.

Now the Angular framework is just as fast as alternatives. When compared to AngularJS, Angular can be more than 5X faster.

The Angular CLI also makes minifying production bundle sizes a breeze, keeping Angular light weight for production.

Advantages of Angular

Angular offers many advantages over the original AngularJS:

Performance:

Angular is up to 5X faster than AngularJS. This is because of a superior diffing algorithm featuring unidirectional data flow and component based architecture.

Server side rendering

Angular offers extensions for rendering your application server side. This is huge for SEO as certain web crawlers can't always scrape async content.

Mobile development

As a framework, Angular makes it possible to develop applications that work on both browsers and native devices like iOS and Android.

Lazy loading

Lazy loading allows you to asynchronously load JavaScript components based on route. This can offer additional performance advantages as code is only imported when it's being used.

Tooling

The tooling provided by TypeScript and the NodeJS ecosystem can't be underestimated. Using the Angular CLI, you can quickly generate Angular components, services, directives etc. without having to manually copy / paste a bunch of boilerplate code.

Additionally, you can more easily build and deploy your project using the CLI.

Should I use Angular or AngularJS?

With the performance advantages, Angular may seem like the best bet moving forward. There is a substantial learning curve to understanding the NodeJS / TypeScript ecosystem and one of the few advantages of AngularJS is that it just runs in the browser.

Using AngularJS makes sense if you have a small application and don't want to bother with learning the ins and outs of NodeJS and TypeScript.

There are also many existing projects out there that already use AngularJS and migrating to newer versions may not justify the cost of learning and rewriting code.

Outside of these cases, adopting "Angular" over the original "AngularJS" is preferred moving forward.

Thanks for reading

If you liked this post, share it with all of your programming buddies!

Follow us on Facebook | Twitter

Further reading about Angular

Angular 8 (formerly Angular 2) - The Complete Guide

Angular & NodeJS - The MEAN Stack Guide

The Complete Node.js Developer Course (3rd Edition)

The Web Developer Bootcamp

Best 50 Angular Interview Questions for Frontend Developers in 2019

How to build a CRUD Web App with Angular 8.0

React vs Angular: An In-depth Comparison

React vs Angular vs Vue.js by Example

Microfrontends — Connecting JavaScript frameworks together (React, Angular, Vue etc)

Building CRUD Mobile App using Ionic 4, Angular 8

How to Build Mobile Apps with Angular, Ionic 4, and Spring Boot

Ionic 4 & Angular Tutorial For Beginners - Crash Course