codelord.net

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

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!

Testing Components with $onChanges Using angular-stub-changes

| Comments

My previous post showed how to set up a component’s controller for unit testing using the $componentController service. We also learned that Angular doesn’t trigger the different lifecycle hooks by itself, meaning that you need to manually call $onInit, etc.

In this post I’ll show an example for testing a component that makes use of the $onChanges hook.

Take a look at this simple word-counting component’s $onChanges hook:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
app.component('wordCount', {
  template: `
    <div>
      <span ng-bind="$ctrl.words"></span> words
      <span ng-if="$ctrl.difference">
        <span ng-bind="$ctrl.difference"></span>
        since last save
      </span>
    </div>
  `,
  bindings: {
    text: '<'
  },
  controller: function() {
    this.$onChanges = (changes) => {
      if (changes.text) {
        this.words = countWords(this.text);
        if (changes.text.isFirstChange()) {
          this.difference = 0;
        } else {
          this.difference =
              this.words - countWords(changes.text.previousValue);
        }
      }
    };

    function countWords(text) {
      var trimmed = text.trim();
      if (trimmed.length === 0) return 0;
      return trimmed.split(/\s+/).length;
    }
  }
});

As you can see, the hook uses the changes object in order to know when the text has changes, detect the initial change, and also use the previousValue to calculate the word difference (yes, I know we could use the old words value, but this is just for the example).

You can see the component live here.

Now, testing this component is relatively trivial. We simply need to pass it some different values for text, trigger $onChanges, and that’s it. But, the fact is that Angular, for some reason, doesn’t expose the changes object it uses internally. That means that you’ll have to implement your own object that conforms to the changes object protocol–each changed property needs an isFirstChange method and 2 properties, currentValue and previousValue.

Since that’s a PITA, I’ve open sourced a tiny helper just for that, angular-stub-changes.

Using it, our tests now look like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
describe('wordCount component', function() {
  var ctrl;

  beforeEach(function() {
    angular.mock.module(app);
    angular.mock.inject(function($componentController) {
      ctrl = $componentController('wordCount', null,
                {text: '1 2 3'});
    });
  });

  it('counts words', function() {
    var changes = new StubChanges().addInitialChange(
        'text', '1 2 3').build();
    ctrl.$onChanges(changes);

    expect(ctrl.words).toBe(3);
  });

  it('does not show difference when initializing', function() {
    var changes = new StubChanges().addInitialChange(
        'text', '1 2 3').build();
    ctrl.$onChanges(changes);

    expect(ctrl.difference).toBe(0);
  });

  it('calculates difference when changing text', function() {
    var changes = new StubChanges().addInitialChange(
        'text', '1 2 3').build();
    ctrl.$onChanges(changes);

    ctrl.text = '1 2 3 4 5';

    changes = new StubChanges().addChange(
        'text', '1 2 3 4 5', '1 2 3').build();
    ctrl.$onChanges(changes);

    expect(ctrl.difference).toBe(2);
  });
});

Basically, note that we make sure to call $onChanges with a properly configured changes object. Also, you still have to set the updated properties on your controller instance yourself, e.g. ctrl.text = '...'.

The creation of the stub changes object is, I hope, straightforward. It’s a builder pattern, so you can keep on adding how many changes (.addChange(..).addChange(..)) as needed for your component

That’s about it, happy testing!

“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!

Unit Testing Angular Components with $componentController

| Comments

Angular 1.5+’s components are great, but testing them properly requires some changes to they way you were used to testing before.

Directives were always a bit clunky to test in Angular. You would either have to deal with recreating their DOM elements, or exposing the controller outside of the directive in order to test it directly. Since components are essentially wrappers around directives, you might expect the same dance.

But, along the introduction of components we also got the handy $componentController service. This service enables testing a component’s controller even without exposing it, and it also provides a simple way to supply a controller with bindings in the test.

Say that we have this component:

1
2
3
4
5
6
7
8
app.component('foo', {
  bindings: {
    baz: '<',
    bar: '<'
  },
  controller: function() {},
  templateUrl: 'foo.html'
});

In order to get an instance of foo’s controller in a test, we’d write this code:

1
2
3
4
var fooCtrl = $componentController('foo', null, {
  baz: 'baz value',
  bar: 'bar value'
});

As you can see, $componentController receives the name of the component that we’d like to test and also the bindings it should be initialized with, and returns the instantiated controller.

You can now start testing the controller, by invoking its functions and asserting the different results:

1
expect(fooCtrl.getDisplayResult()).to.equal('baz value bar value')

Don’t forget $onInit

In case your component implements the $onInit lifecycle hook, which is very likely starting from Angular 1.6, you should make sure to explicitly call it in your tests. Angular and $componentController does not take care of that for you, for different reasons.

This means that the test above should look like this:

1
2
3
var fooCtrl = $componentController('foo', null, {...});
fooCtrl.$onInit();
expect(fooCtrl.getDisplayResult()).to.equal('baz value bar value')

That’s it!

Handling $onChanges is even trickier in tests, make sure to subscribe below to get the next part about it.

“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 1.6 is here: what you need to know

| Comments

Angular 1.6 was released a few weeks ago (and actually 1.6.1 was released a week ago). I’m so happy to see the Angular team keep spending time in making 1.x better and improving it.

As opposed to 1.5, 1.6 doesn’t introduce a lot of new features or changes, which I think is a good thing. I believe most 1.x projects have yet to integrate 1.5’s components properly, and so adding more changes might be overwhelming.

1.6 is more of a clean up release, that, in order to fix bugs and remove deprecations, introduces a handful of breaking changes.

I’ll go over the ones that I’m sure will trip a lot of people up. You can see the full, really long, list here.

Controller pre-assignment of bindings–or $onInit all the things

1.6 changes the default behavior of $compile in that it no longer, by default, initializes a controller’s bindings before $onInit is called (the new lifecycle hook introduced in 1.5, you can read more about it here).

What does that mean? Looking at this example:

1
2
3
4
5
6
7
8
app.component('foo', {
  bindings: {
    baz: '<'
  },
  controller: function() {
    this.baz.something();
  }
});

The above code will no longer work, since we’re accessing the baz binding inside the controller’s constructor function directly.

To change it to work, you should make sure to move all of your controller’s initialization code to be inside the $onInit hook:

1
2
3
4
5
6
7
8
9
10
app.component('foo', {
  bindings: {
    baz: '<'
  },
  controller: function() {
    this.$onInit = () => {
      this.baz.something();
    }
  }
});

Note: I’m using ES6 arrow functions for brevity.

In case you’ve already adopted your code to use $onInit you’re all good. Also, since most style guides, e.g. John Papa’s, have recommended the use of an init() function of sorts in controllers for quite a while, I’m assuming for most projects this is not a big deal. Simply rename your current init() functions to be $onInit methods.

What if you don’t want to go over all controllers right now?

In case you don’t have the time or energy to change all your controllers now, but still want to upgrade to 1.6, you can re-enable the old behavior:

1
2
3
app.config(function($compileProvider) {
  $compileProvider.preAssignBindingsEnabled(true);
});

But keep in mind that this is likely to be removed in a future version of Angular.

$onInit won’t work for standalone controllers

Standalone controllers are controllers that aren’t defined as part of a directive or component. Most commonly, these are controllers used as part of route definitions, or, heaven forbid, ng-controller.

Standalone controllers do not get the lifecycle hooks, and don’t have bindings anyway, so just make sure not to accidentally try and update them too in your migration frenzy. It won’t work.

$http.success and $http.error are finally gone

I’m really hoping not a lot of people are still using these relics of older Angular days, but I keep coming across projects that use it here and there (I believe old blog posts all over the web are at fault, most people aren’t aware of the difference when just starting).

I’ve written about why you shouldn’t be using them almost 2 years ago, and they’ve since been deprecated.

Well, 1.6 has finally killed them. If you’re still using them for some reason, here’s a great excuse to spend 20 minutes and use proper promises everywhere.

Upgrade and enjoy!

“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!

Replacing Angular’s Deep Watches with the $doCheck Lifecycle Hook

| Comments

After digging into Angular’s components $onChanges lifecycle hook to show how you can replace a regular shallow $scope.$watch with it, let’s see what the latest Angular has to offer when it comes to deep watches.

Deep watches are what Angular does when you supply a third argument to $scope with the value of true:

1
$scope.$watch(() => this.foo, this.handleChange, true);

Note: I’m using ES6’s arrow functions for brevity, but obviously you don’t have to.

By using deep watches, we can ask Angular to keep track of changes happening inside an object, by mutating it, instead of only notifying us when the object’s reference has changed (which is the default behavior of $scope.$watch).

While it’s possible to use $onChanges for being notified about changes to references on bindings, there’s no easy way to do it for mutations without $scope.$watch.

The problem is that Angular is moving off $scope, and we would like to be able to use it only where it’s really a must, so what can we do?

First, think whether you really need to be mutating state. In a lot of scenarios, using immutable models makes a lot more sense, and using one-way data flow makes code easier to maintain.

But, in cases you have to keep using deep watches, there’s some more modern solution offered by Angular. The $doCheck lifecycle hook is a bit peculiar. It’s basically a hook that Angular calls on each turn of the digest cycle, for us to add our logic in it. That allows us to regularly check if anything has changed and requires our component’s attention.

What this enables us to do, in practice, is replace our deep watches. Here’s an example:

1
2
3
4
5
6
7
8
9
10
11
12
function FooCtrl() {
  var previousFoo = undefined;

  this.$onInit = () => { previousFoo = angular.copy(this.foo) };

  this.$doCheck = () => {
    if (!angular.equals(this.foo, previousFoo)) {
      this.handleFooChange();
      previousFoo = angular.copy(this.foo);
    }
  };
}

Now, this is a bit of a mouthful. As you can see, when we want to drop deep watches we actually have to do quite some work on our own: keep track of the previous value, make the comparison, and make sure we are holding a copy of the value (otherwise we’ll never see changes).

Angular is basically telling us that deep watches belong to the past, and that there’s a way to keep doing them without scopes, but you’ll need to work for it. Personally, I don’t love the extra typing, but I think that if you have to keep using deep watches for now and are upgrading your code to the latest 1.6 standards, you should probably be doing this.

Nowadays, a modern Angular app should be making very small use of scopes, and deep watches are a big red flag usually. This makes sense both from the standpoint of moving to a one-way data flow, and for keeping your options open when it comes to migrating to Angular 2+ down the road.

“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!

Replacing $scope.$watch with Lifecycle Hooks

| Comments

It is not uncommon to have an Angular directive or component that needs to perform some work when its bounded inputs are changed.

And we all know watches are bad for performance, and that you should only use them when you really need them. But sometimes your code really needs them. What to do?

With Angular 1.5’s introduction of components, and the back-porting of lifecycle hooks from Angular 2, we have cleaner ways of achieving this.

Note: This post will use components, but lifecycle hooks are available in Angular’s directive as well. You can make use of this technique even if your team hasn’t moved to components yet, as long as you’re using Angular 1.5 or later.

Let’s look at a an example component. For brevity I’ll be using ES6’s arrow functions, but of course you don’t have to:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
app.component('chart', {
  templateUrl: 'chart.html',
  bindings: {
    dataSeries: '='
  },
  controller: function($scope) {
    this.$onInit = () => {
      $scope.$watch(() => this.dataSeries, () => this._updateChart());
    };

    this._updateChart = () => {
      // Some D3 code to update the chart
    };
  }
});

As you can see, this is a very basic component that wraps around some native D3 code to render a chart. Whenever its input binding, dateSeries, is changed the component re-renders the chart. And it keeps track of those changes using $scope.$watch.

Now, let’s make use of the $onChanges lifecycle hook. $onChanges is called automatically by Angular whenever an input binding is changed by the component’s parent.

A couple of important details to notice: $onChanges only works with one-way bindings (and @ bindings), which is what you should be using 99% of the time, and $onChanges is only triggered when the parent component reassigns the value. It will not be triggered if you reassign it inside the component itself.

So let us update our component to use one way bindings and $onChanges instead of a watch:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
app.component('chart', {
  templateUrl: 'chart.html',
  bindings: {
    dataSeries: '<' // Changed to one way
  },
  controller: function() {
    this.$onChanges = (changes) => {
      if (changes.dataSeries) {
        this._updateChart();
      }
    };

    this._updateChart = () => {
      // Some D3 code to update the chart
    };
  }
});

That’s about it. We no longer need to inject $scope, which is always a good thing. And we also removed a watch: Angular has its own watch on the binding anyway in order to sync it between components, and we’re taking advantage of it.

Detecting the Initialization Call

Sometimes when using $watch we would like to treat the first time it is called differently, since $watch triggers immediately after starting a watch. The way we identify it would be to write code such as this:

1
2
3
4
5
$scope.$watch(() => this.foo,
  (newValue, oldValue) => {
    if (newValue === oldValue) return;
    this.updateView();
});

As you can see, we’d check if newValue is the same as oldValue, which is Angular’s way of telling us it’s the initial run of the watcher.

With $onChanges we have a clearer way of achieving this:

1
2
3
4
5
this.$onChanges = (changes) => {
  if (changes.foo && !changes.foo.isFirstChange()) {
    this.updateView();
  }
};

As you can see, the changes object comes with a handy isFirstChange() method.

Keeping Track of the Previous Value

Another useful capability of $watch is that whenever it was triggered it would supply our listener with both the current value and the previous value. This allows the code to compare them:

1
2
3
4
5
6
$scope.$watch(() => this.foo,
  (newValue, oldValue) => {
    if (newValue.date !== oldValue.date) {
      this.updateView();
    }
});

Fear not, the changes object still got you covered:

1
2
3
4
5
6
7
8
this.$onChanges = (changes) => {
  if (!changes.foo) return;
  if (changes.foo.currentValue.date === changes.foo.previousValue.date) {
    return;
  }

 this.updateView();
};

Gotcha: $onChanges and $onInit

It just so happens that Angular triggers the initial $onChanges right before calling the $onInit hook. You should be aware of that when you write your component’s lifecycle hooks and make sure that you don’t rely in $onChanges on anything that gets setup by $onInit, and if so, make sure to account for it on the first change call.

That’s it! You just got rid of some needless $scope.$watch calls. Better performance, and modern code – win!
Pat yourself on the back for me.

“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!

Video Walkthrough: Refactoring Angular Components to Use Require Mechanism

| Comments

Continuing from my previous post about advanced component communication with Angular’s require mechanism, I decided to try and walkthrough such an example refactoring, based on real code I’ve seen multiple times.

This shows the actual steps you need to take to change existing code to use require and also shares some of my philosophy on when it should be used.

This is my first video ever, and I’d love to hear your feedback!

The source code for the before and after states is available on GitHub.

“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!