codelord.net

Code, Angular, iOS and more by Aviv Ben-Yosef

ng-annotate Deprecated: What That Means for Your Projects

| Comments

For several years, the handy ng-annotate has helped save countless developers hours and debugging sessions, by automatically inserting Angular’s dependency injection annotations to code instead of developers having to maintain them by hand.

But, alas, it has been deprecated. Read on to understand what that means for your projects currently using it.

You Don’t Need to Type Annotations by Hand

Just because ng-annotate is deprecated it doesn’t mean it’s going to stop working. If it’s working for you right now, you can keep using that version and things should work as they have.

But, the “official” successor of ng-annotate is babel-plugin-angularjs-annotate (BPAA).

BPAA is actually a fork of ng-annotate that has been around for a while. While ng-annotate operated on JS source files, and had to be passed ES6 code after transpilation, BPAA is a Babel plugin and so operates as part of the transpilation process, and in a relatively transparent manner.

Given a build process/toolchain that’s already set up to use Babel, adding BPAA is often easier than adding ng-annotate. How much easier? You can follow the README I linked to above, but it generally boils down to a single NPM dependency and modifying a single line in your Babel configuration.

Since ng-annotate will no longer be maintained, I recommend switching to BPAA once you get the chance (nothing urgent though). I went through this process at a recent client and it was fairly simple and took less than an hour.

It also seems that BPAA is faster than ng-annotate, which makes for faster build times, that’s a small win.

Implicit Detection Considered Harmful

As part of the deprecation, the maintainers of both ng-annotate and BPAA agreed that implicit annotation detection is a bad practice and should be avoided.

What’s does that mean? Implicit detection means that the tools try and understand from the code whenever an Angular injectable is being declared and automatically insert annotations for it as needed, without any manual steps necessary by developers.

The maintainers talk about implicit detection causing a lot of problems, and recommend running BPAA with the explicitOnly setting. That setting means that you will need to markup class constructors like so:

1
2
3
4
5
6
class SomeCtrl {
  constructor($http) {
     'ngInject'; // <-- BPAA looks for this
    // ...
  }
}

And same goes for injectable functions:

1
2
3
4
5
angular.module('app').config(function($httpProvider) {
  'ngInject';

  // ...
});

This might seem weird if this is the first time you come across explicit mark up, but it’s easy enough and, along with strict-di, makes it impossible to come across injection bugs in runtime. While it would’ve been great if these explicit markers weren’t necessary, but since in most projects there’s at least one use case where they’re required I can see the logic of choosing the explicit route for safety.

“But I’m Not Using ES6!”

Well, surprisingly enough, you can incorporate Babel into your build process with BPAA as described above, to replace your existing ng-annotate step.

Babel doesn’t have to transpile ES6. If you don’t provide it with an ES6 (or ES2015, or whatever) preset, and just configure the BPAA plugin, Babel can be used instead of ng-annotate.

Open source sometimes moves fast, but the important point is that there’s a clear and relatively easy way to start using the supported tool (BPAA), and keep saving countless bugs and keystrokes!

“Maintaining AngularJS feels like Cobol 🤷…”

You want to do AngularJS the right way.
Yet every blog post you see makes it look like your codebase is obsolete. Components? Lifecycle hooks? Controllers are dead?

It would be great to work on a modern codebase again, but who has weeks for a rewrite?
Well, you can get your app back in shape, without pushing back all your deadlines! Imagine, upgrading smoothly along your regular tasks, no longer deep in legacy.

Subscribe and get my free email course with steps for upgrading your AngularJS app to the latest 1.6 safely and without a rewrite.

Get the modernization email course!

Fixing Angular Template Overuse

| Comments

Templates in AngularJS are quite powerful, but just because something can be done in the template doesn’t mean you should do it there. The separation between controller and template can be vague in Angular, which is why I have a couple of guidelines which I consider to be best practices in any Angular project.

One of those rules of thumb is: Don’t do in the template what can be done elsewhere.

In this post, I will go over the different symptoms of template overuse and why it can be problematic.

Template Overuse Symptoms

Template Overuse (noun): Performing work in the template that will be better placed somewhere else.

ng-click

A popular example is ng-click abuse:

1
2
3
<button ng-click="$ctrl.validate() && $ctrl.submit()">
  Submit
<button>

As you can see, the ng-click handler is first making sure that the form is valid before actually calling the submit operation.

This extra logic is misplaced.

A similar, yet different, example is:

1
<button ng-click="$ctrl.counter = 0">Reset</button>

As a guideline, template event handlers should trigger functions on the controller, and not any other expression/statement (e.g. the above would be ng-click="$ctrl.reset()").

This goes the same for similar directives, such as ng-submit, etc.

ng-init

This, for some reason beyond me, is not an uncommon sight:

1
<div ng-init="$ctrl.setup()">

In case you’re not aware of it, ng-init simply runs the code given to it when the template initializes. Its valid use cases are so rare, even the documentation warns against using it.

And yet, a GitHub search comes up with 785K+ hits at the time of this writing.

There’s a good place to initialize stuff: the controller’s $onInit hook!

Underusing CSS

All the power we get from templates might make it easy to forget that not all visual logic has to be done inside them. A good example is using ng-if or ng-class for targeting special cases that can be handled in CSS, like special casing the first element in a list, or coloring every other row, like I’ve shown here.

Forgetting the Basics

I see too many developers reinventing the wheel instead of making use of the power of the web.

Consider the first example here, which showed ng-click="$ctrl.validate() && $ctrl.submit()". There’s a known mechanism for preventing actions on buttons in case the form state is invalid, which is setting those buttons to be disabled. This can be done by using Angular’s validators, or even simply by using ng-disabled:

1
2
3
<button ng-disabled="!$ctrl.validate()" ng-click="$ctrl.submit()">
  Submit
</button>

Why is Overuse Bad?

First, having extra logic in the template makes it harder to refactor code at a later point. I’ve yet to come across the perfect IDE that makes refactoring templates as smooth as refactoring JavaScript code. If that’s the case, I opt for the style that makes refactoring easier.

Further, it’s very easy for templates to contain a bunch of dense expressions and overly long ng-if conditions. These in turn make code maintenance a PITA. Templates should be easy to change when view requirements change, and are best when they make it easy to understand and visualize what is happening on screen. The more code in your templates, the harder they become to follow.

Also, logic in template also makes it harder to properly unit test controllers. For example, if the template contains an ng-init hook, then usually the test would also have to invoke whatever expression the ng-init is calling.

Essentially, all these reasons boil down to complicated templates making code maintenance harder in the long term. Making a point of keeping templates succinct will make for a codebase that everyone will be happier working on.

Fixing Overuse

To repeat, the basic guidelines you should strive to follow are:

  1. Don’t do in the template what can be done elsewere.
  2. Template event handlers should trigger functions.
  3. Remember the basics, like CSS and HTML form validation.
  4. Don’t use ng-init. Just don’t.

“Maintaining AngularJS feels like Cobol 🤷…”

You want to do AngularJS the right way.
Yet every blog post you see makes it look like your codebase is obsolete. Components? Lifecycle hooks? Controllers are dead?

It would be great to work on a modern codebase again, but who has weeks for a rewrite?
Well, you can get your app back in shape, without pushing back all your deadlines! Imagine, upgrading smoothly along your regular tasks, no longer deep in legacy.

Subscribe and get my free email course with steps for upgrading your AngularJS app to the latest 1.6 safely and without a rewrite.

Get the modernization email course!

The Magic Properties of Angular’s ng-repeat

| Comments

One of the basic building blocks of Angular is, of course, the ng-repeat directive. It’s certainly one of the things newcomers pick up right when starting to learn Angular. Yet, it’s very easy to just learn the basics and miss out on some of its lesser known but useful features.

In this post you will learn what automatic properties ng-repeat creates on the scope object, to make common tasks easier.

$index

The scope property is most probably the most popular one. When using ng-repeat, every block of repeated content has access to a property called $index. This property is a number, and contains the current index of the “loop” ng-repeat is doing:

1
2
3
<div class="task" ng-repeat="task in $ctrl.tasks">
  <span ng-bind="$index"></span>: <span ng-bind="task.name"></span>
</div>

As you can probably guess, this will display next to each task’s name its index in the $ctrl.tasks array.

Yet while it is most known, it is probably the one that should be used the least.

$first and $last

It’s common when using ng-repeat to add specific behavior to the first or last element of the loop, e.g. special styling around the edges.

I’ve seen too many programmers do it awkwardly using $index:

1
<div ng-if="$index == $ctrl.tasks.length - 1">Last</div>

Instead, ng-repeat already supplies you with two ready boolean properties. $first is true for the first element, and $last is true for the last element.

While we’re at it, I’ll mention that if all you’re doing here is styling, e.g. ng-class according to the first/last index, you might be better off doing this purely in CSS using the :first-child and :last-child pseudo-classes.

$middle

This simple property is simply used to tell whether the current element is neither the first element in the loop, nor the first.

It’s equivalent to !$first && !$last (to please the logic nerds, this is also !($first || $last), according to De Morgan’s Laws).

$odd and $even

These properties simply state whether the current $index is odd or even. It’s very common to style grid with alternating colors between rows for easier readability, and if you’re using ng-class to add an .even class, you’d better use $even instead of $index % 2 == 0.

Yet, again, I’ll say that in case you’re using this solely for styling, doing this in CSS would probably be the better choice, e.g. :nth-child(odd) and :nth-child(even).

You can read more about these properties and ng-repeat’s other features in the documentation.

“Maintaining AngularJS feels like Cobol 🤷…”

You want to do AngularJS the right way.
Yet every blog post you see makes it look like your codebase is obsolete. Components? Lifecycle hooks? Controllers are dead?

It would be great to work on a modern codebase again, but who has weeks for a rewrite?
Well, you can get your app back in shape, without pushing back all your deadlines! Imagine, upgrading smoothly along your regular tasks, no longer deep in legacy.

Subscribe and get my free email course with steps for upgrading your AngularJS app to the latest 1.6 safely and without a rewrite.

Get the modernization email course!

Understanding Optional AngularJS Bindings

| Comments

It seems that few developers are familiar with the ability to mark bindings in AngularJS as optional, and what that even means. After all, you may have seen that even when you don’t pass a binding to a directive/component, things seem to work, so why bother?

In this post we’ll go over the different binding types and understand what, exactly, setting them as optional means, so you’ll know when to use it and what might happen if you don’t.

Two-way = bindings

Two-way bindings, when not specified as being optional, would only complain when the component tries to assign to them. That is because, by definition, Angular would attempt to update the parent component as well. If the parent never gave a value, Angular will not be able to update it, and so would throw a runtime exception.

For example, consider a component called userEditor that defines its bindings like this:

1
2
3
bindings: {
  user: '='
}

If you were to instantiate the component without the user bindings, e.g. <user-editor></user-editor>, at first nothing bad would happen. The component’s controller, when accessing the this.user property, will see that its value is undefined.

But, if the component would ever attempt a reassignment, such as this.user = {}, it would result in an error.

In those situations, in case the binding is not mandatory, you should specify it as being optional:

1
2
3
bindings: {
  user: '=?'
}

Then, reassigning would just silently work, without actually updating anything in the parent.

Though, I will stress that reassignments should be rare and you should probably be using one-way bindings, described below.

One-way < bindings

Since one-way bindings are, hmm, one-way, they don’t have the same problem as described above on reassignments. Angular just doesn’t care that the component is reassigning, and so, for these bindings, the behavior would be the same with or without the optional setting. If the user of the component does not pass a value for the binding, it would be undefined in the component’s controller and that’s it.

Yet it can be specified as being optional, by providing the value <? in the bindings definition (or scope if you’re using a directive).

Expression (function) & bindings

The & binding is mostly used in order to pass a callback to a component–a simple function that can be invoked by the component’s controller.

By default, when these bindings aren’t set up with an initial value by the parent component, they simply translate to a function that does nothing and returns undefined (also known as angular.noop). This makes it completely safe for the child component to call that binding without risking a crash, as a nice example of the Null Object pattern.

And yet, sometimes the component would need to know whether the callback was passed at all or not, e.g. to decide whether certain work needs to be done.

In those scenarios it is possible to specify the binding as being optional, with &?, and then it is passed to the controller as undefined, instead of angular.noop. Then the controller can check for it, e.g. if (this.callback), and take action according to the value.

This does mean, though, that the controller can no longer blindly invoke the binding; it has to check first that it is defined.

Bottom Line: Use Optional If You Mean It

As you might understand, one can do Angular for quite a while without ever having to use optional bindings. And yet, I would argue that they should always be used if, indeed, the bindings are optional.

Also since in two-way bindings it would be a bug waiting to happen to do otherwise. Yet mainly because I believe that doing so helps to write better, more maintainable code, that is later easier for future users of the component to reason about and understand (be those users other developers or future-you).

By adopting a convention across your codebase to always specify optional bindings when necessary, your team will have another aid for explicitly documenting your code.

Just remember to add that ? to the binding definition!

“Maintaining AngularJS feels like Cobol 🤷…”

You want to do AngularJS the right way.
Yet every blog post you see makes it look like your codebase is obsolete. Components? Lifecycle hooks? Controllers are dead?

It would be great to work on a modern codebase again, but who has weeks for a rewrite?
Well, you can get your app back in shape, without pushing back all your deadlines! Imagine, upgrading smoothly along your regular tasks, no longer deep in legacy.

Subscribe and get my free email course with steps for upgrading your AngularJS app to the latest 1.6 safely and without a rewrite.

Get the modernization email course!

Converting Angular Controllers to ES6 Classes

| Comments

After covering the process of transforming Angular services to ES6 classes, and digging into how injection works with ES6 classes, it’s time to take a closer look at controllers.

Controllers, being the basic building block in Angular, is also where you’ll get your biggest bang-for-the-buck for making the ES6 transition, in my opinion. That is, assuming your project is already making use of controller-as syntax, as opposed to exposing all of your controllers’ logic directly on the $scope object.

Let us look at an example controller:

1
2
3
4
5
6
7
8
9
10
11
12
function UsersCtrl(UsersStore) {
  var self = this;
  self.$onInit = function() {
    UsersStore.get().then(function(users) {
      self.users = users;
    }):
  };

  self.updateUser = function(user) {
    UsersStore.updateUser(user);
  };
}

(Note how all initialization is taking place inside the $onInit hook, which is a must starting from 1.6+)

Here is how the above controller would be written as a class:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class UsersCtrl {
  constructor(UsersStore) {
    this.UsersStore = UsersStore;
  }

  $onInit() {
    this.UsersStore.get().then(users => {
      this.users = users;
    });
  }

  updateUser(user) {
    this.UsersStore.updateUser(user);
  }
}

The conversion steps are:

  1. Change the function to be a class definition
  2. Create inside it a constructor and move all injections to be its parameters. Inside this constructor assign every injected service to be a member of the new class.
  3. Change every method declared previously as this.function to be declared as a regular method in a class.
  4. Update all references to injected services to use the local properties, e.g. this.UsersStore instead of UsersStore.

Keep in mind that while classes have a constructor, you should not be using them for any real logic. You want to keep them as stupid as possible, only making sure to save injections. All other logic should be kept inside the $onInit hook.

Also note that ES6 classes do not have a concept of private methods/members. In the function syntax you could have declared a var innerData inside the UsersCtrl function, and innerData would not have been accessible to the template. That’s not the case with classes, and so I usually opt for a naming convention where templates are not allowed to access any methods or members on the controller that start with a _, e.g. _innerData.

You might find it icky, but that’s just the way it is. TypeScript, which you might also be considering, supports private members and even saves you the constructor boilerplate.

“Maintaining AngularJS feels like Cobol 🤷…”

You want to do AngularJS the right way.
Yet every blog post you see makes it look like your codebase is obsolete. Components? Lifecycle hooks? Controllers are dead?

It would be great to work on a modern codebase again, but who has weeks for a rewrite?
Well, you can get your app back in shape, without pushing back all your deadlines! Imagine, upgrading smoothly along your regular tasks, no longer deep in legacy.

Subscribe and get my free email course with steps for upgrading your AngularJS app to the latest 1.6 safely and without a rewrite.

Get the modernization email course!

Angular Dependency Injection Annotations With ES6 Classes

| Comments

After covering how ES6 classes can be used for defining services in Angular in the previous post, I was asked how do these play along with Angular’s dependency injection annotations.

To recap, dependency injection annotations are used so that Angular would know what it should be injecting even when code is obfuscated/minified. This is a regular service with injection in ES5:

1
2
3
angular.module('app').service('Service', function($http) {
  this.get = function() { ... };
});

And that example with explicit annotations would look like so:

1
2
3
angular.module('app').service('Service', ['$http', function($http) {
  this.get = function() { ... };
}]);

How does this play along with ES6 classes?

The above example as a class looks like this:

1
2
3
4
5
6
7
8
angular.module('app').service('Service', Service);

class Service {
  constructor($http) {
    this.$http = $http;
  }
  get() { ... }
}

And in order to add proper annotations to it, simply add this line at the bottom:

1
Service.$inject = ['$http'];

That’s all there’s to it, if you insist on adding these manually.

But please, stop doing it like an animal, and incorporate something like babel-plugin-angularjs-annotate. Given that you’re using ES6, you very likely already transpiling your code into ES5, and this plugin can simply go over your code at that point and add these as necessary, given little hints. I’ve written more about it here.

Keep it classy! </dadpun>

“Maintaining AngularJS feels like Cobol 🤷…”

You want to do AngularJS the right way.
Yet every blog post you see makes it look like your codebase is obsolete. Components? Lifecycle hooks? Controllers are dead?

It would be great to work on a modern codebase again, but who has weeks for a rewrite?
Well, you can get your app back in shape, without pushing back all your deadlines! Imagine, upgrading smoothly along your regular tasks, no longer deep in legacy.

Subscribe and get my free email course with steps for upgrading your AngularJS app to the latest 1.6 safely and without a rewrite.

Get the modernization email course!

Moving Angular Factories to Services With Classes

| Comments

When I first wrote about the differences between services and factories in Angular, the bottom line was that the difference is semantic and so you should just pick one and stick with it.

Back then I made the point that, personally, I find factories require less boilerplate code and so they are often my choice.

Since then, a use case for using services has become more common, and that’s when using ES6/ES2015 classes.

When making use of classes, services are the right choice.

That’s because classes map naturally to an Angular service, let’s see how.

Take a look at this non-ES6 UsersStore:

1
2
3
4
5
6
angular.module('app').factory('UsersStore', function($http) {
  return {
    getAll: function() { ... },
    get: function(id) { ... }
  };
});

Converting this to an ES6 class would look like this:

1
2
3
4
5
6
7
8
class UsersStore {
  constructor($http) {
    this.$http = $http;
  }

  getAll() { ... }
  get(id) { ... }
}

The registration line would then be changed to this:

1
angular.module(app).service(UsersStore, UsersStore)

The behavior for all existing code that injects UsersStore will remain the same, this is a seamless transition.

An important note, though, is the way injection is now performed. Note that $http is now provided to the class’s constructor. In order to be able to access the injected service later, for example in the getAll method, we have to save it as a member. Then, the code in the converted getAll function should make sure to reference it as this.$http.

The extra typing around a constructor might put off some people, but looking at the bright side I find it helps making it more painful to write uber controllers and services that take on too much responsibility :)

Subscribe below to learn more about modern Angular and using Angular with ES6.

“Maintaining AngularJS feels like Cobol 🤷…”

You want to do AngularJS the right way.
Yet every blog post you see makes it look like your codebase is obsolete. Components? Lifecycle hooks? Controllers are dead?

It would be great to work on a modern codebase again, but who has weeks for a rewrite?
Well, you can get your app back in shape, without pushing back all your deadlines! Imagine, upgrading smoothly along your regular tasks, no longer deep in legacy.

Subscribe and get my free email course with steps for upgrading your AngularJS app to the latest 1.6 safely and without a rewrite.

Get the modernization email course!

Screencast: Debugging Bad Performance in an AngularJS App

| Comments

This is a video walkthrough of the debugging process of a slow AngularJS app, until pinpointing the exact deep $watch that is causing the performance bottleneck. See how tools such as ng-stats, profiling in the Chrome Dev Tools and editing Angular’s code come together to solve this issue!

“Maintaining AngularJS feels like Cobol 🤷…”

You want to do AngularJS the right way.
Yet every blog post you see makes it look like your codebase is obsolete. Components? Lifecycle hooks? Controllers are dead?

It would be great to work on a modern codebase again, but who has weeks for a rewrite?
Well, you can get your app back in shape, without pushing back all your deadlines! Imagine, upgrading smoothly along your regular tasks, no longer deep in legacy.

Subscribe and get my free email course with steps for upgrading your AngularJS app to the latest 1.6 safely and without a rewrite.

Get the modernization email course!

The Performance Difference Between ng-bind and {{}}

| Comments

Interpolation is one of the first things newcomers to Angular learn. You can’t get around writing your first Angular “Hello, World” without some sort of simple interpolation like Hello, {{ $ctrl.name }}.

But, you may have come across the ng-bind directive, seen it used and realized it’s pretty much the same as straightforward interpolation. The above example using ng-bind would look like this:

1
Hello, <span ng-bind="$ctrl.name"></span>

Why do we have both {{}} and ng-bind?
Is there any reason to use one over the other?
In this post we’ll see exactly what are the differences and why ng-bind is preferable.

The original reason: Flash Of Unstyled Content

FOUC is a term that’s been around for quite some time. In Angular, it mostly refers to when a user might see a flash of a “raw” template, before Angular actually got to compiling it and handling it correctly. This happens from time to time when using {{ }} interpolation, since Angular has to go over the DOM, find these and actually evaluate the proper value to put in them.

It looks unprofessional and also might make non-technical people think there’s something wrong with the page.

ng-bind, on the other hand, makes this a non-issue. Since the directive operates as an element attribute, and not as the element’s text value, there’s nothing visible to the user before Angular finishes compiling the DOM.

This can also be circumvented using plain {{ }} by using tricks like ng-cloak, but I always found those to be a hassle.

The real reason: Performance

While it might seem like there’s no real reason to have a different performance impact if you’re writing {{ $ctrl.hello }} or <span ng-bind="$ctrl.hello "></span>, there is.

If you’ve been following my posts for a while, this shouldn’t be the first time you hear of a case where 2 things that seem like they should be pretty identical are actually very different when it comes to their run-time performance.

The thing is that when it needs to keep track of interpolated values, Angular will continuously re-evaluate the expression on each and every turn of the digest cycle, and re-render the displayed string, even if it has not changed.

This is opposed to ng-bind, where Angular places a regular watcher, and will render only when a value change has happened. This can have a major impact on the performance of an app, since there is a significant difference in the time each way adds to the digest cycle.

In my benchmarks, I’ve seen it go as far as being twice as fast to use ng-bind. You can see for yourself in these samples: with interpolation vs using ng-bind (and since these are basic interpolations, I wouldn’t be surprised the problem is worse for complicated expressions).

I’m not big for premature optimizations, but I do prefer sticking to a single way of doing things across a project. That is why I usually opt for sticking with ng-bind from the start.

Happy hacking!

“Maintaining AngularJS feels like Cobol 🤷…”

You want to do AngularJS the right way.
Yet every blog post you see makes it look like your codebase is obsolete. Components? Lifecycle hooks? Controllers are dead?

It would be great to work on a modern codebase again, but who has weeks for a rewrite?
Well, you can get your app back in shape, without pushing back all your deadlines! Imagine, upgrading smoothly along your regular tasks, no longer deep in legacy.

Subscribe and get my free email course with steps for upgrading your AngularJS app to the latest 1.6 safely and without a rewrite.

Get the modernization email course!

Techniques for Improving ng-repeat Performance

| Comments

ng-repeat is notorious for often being the biggest performance bottleneck in Angular apps. It is common practice, when performance tuning lists, to use track by or one-time bindings. Surprisingly, trying to combine both of these practices usually has unexpected results. In this post, we’ll go over the different scenarios ng-repeat is usually used for, and the possible improvements for speeding it up ng-repeat.

Note that before diving into any optimizations, I highly suggest measuring and tracking down the problematic parts of your app.

Refreshing the whole list

Scenario

The list you’re rendering with ng-repeat isn’t edited/changed on a per-line basis, but simply reloaded, e.g. with a “Refresh” button that fetches the model again from the server and replaces the currently displayed list.

The act of re-rendering the whole list feels laggy. Usually this means there’s some jank, or the browser seems to freeze for a bit before actually rendering.

Improvement: track by

Use track by as detailed here. In the above scenario, when the list is changed Angular will destroy all DOM elements in the ng-repeat and create new ones, even if most of the list elements remained identical to their previous versions. This, especially when the list is big, is an expensive operation, which causes the lag.

track by lets Angular know how it is allowed to reuse DOM elements in ng-repeat even if the actual object instances have been changed. Saving DOM operations can significantly reduce lag.

A completely static list

Scenario

Your component displays a list of items that’s never changed as long as the component is alive. It might get changed when the user goes back and forth between routes, but once the data has been rendered and until the user moves on to a different place in your app, the data remains the same.

This is common in analytics apps that display results of queries and don’t actually manipulate the data afterwards.

While the list is on the screen the app might feel sluggish when interacting with it, e.g. clicking on buttons, opening dropdown, etc. This is usually caused by the ng-repeat elements introducing a lot of watchers to the app, which Angular then has to keep track of in every digest cycle.

I’ve seen my fare share of apps with simple-looking tables that made an app grind to a halt because under the hood they had thousands of watchers, heavy use of filters, etc.

Improvement: one-time bindings

Just for the case where the data should be rendered for a single time we were given the one-time binding syntax.

See the full explanation here, but basically by sprinkling some :: inside the ng-repeat elements’ bindings, a static list can have the number of watchers reduces to even nothing.

This means that once the rendering has finished the table has no performance impact on the page itself.

Editable content

Scenario

Your app displays a list or a table that can be changed by the user. Maybe some fields can be edited. Or perhaps there’s a table cell with a dynamic widget.

The list is big enough to have the same performance problems discussed in the previous part, but, since it needs to pick up on changes in the data, simply using one-time bindings breaks its usability. The list stops displaying changes, since all our watches are gone.

Improvement: immutable objects and one-time bindings

When you mutate one of the objects inside a list, Angular doesn’t recreate the DOM element for it. And since the DOM doesn’t get recreated, any one-time bindings will never be updated.

This is a great opportunity to start moving into the more modern one-way data flow and use immutable objects.

Instead of mutating the objects, e.g.:

1
2
3
function markTodoAsDone(todo) {
  todo.done = true;
}

… treat your models as immutable. When a change is needed, create a clone of the data and replace the model object inside the list:

1
2
3
4
5
function markTodoAsDone(todo) {
  var newTodo = angular.copy(todo);
  newTodo.done = true;
  todosListModel.replace(todo, newTodo);
}

Why does this work? Consider this template:

1
2
3
4
5
<div ng-repeat="todo in $ctrl.todosListModel.get()">
  <div ng-bind="::todo.title"></div>
  <div ng-if="::todo.done">Done!</div>
  <button ng-click="$ctrl.markTodoAsDone(todo)">Done</button>
</div>

Since all the bindings inside the ng-repeat template are one-time bindings, the only watcher here is the $watchCollection used by ng-repeat to keep track of $ctrl.todosListModel.get().

Had we simply mutated the todo object, the $watchCollection would not get triggered and nothing would get rendered. But since we’re putting a new object inside the list, $watchCollection will trigger a removal of the old todo, and an addition for the new one. The addition will create a new DOM element for our todo, and so it will get rendered according to its latest state.

Summary

ng-repeat can be tamed, at least partially, if you take care to use it according to your specific use case.

I hope this helps you speed your app a bit!

“Maintaining AngularJS feels like Cobol 🤷…”

You want to do AngularJS the right way.
Yet every blog post you see makes it look like your codebase is obsolete. Components? Lifecycle hooks? Controllers are dead?

It would be great to work on a modern codebase again, but who has weeks for a rewrite?
Well, you can get your app back in shape, without pushing back all your deadlines! Imagine, upgrading smoothly along your regular tasks, no longer deep in legacy.

Subscribe and get my free email course with steps for upgrading your AngularJS app to the latest 1.6 safely and without a rewrite.

Get the modernization email course!