codelord.net

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

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!


You want to do Angular the right way.
You hate spending time working on a project, only to find it’s completely wrong a month later.
But, as you try to get things right, you end up staring at the blinking cursor in your IDE, not sure what to type.
Every line of code you write means making decisions, and it’s paralyzing.

You look at blog posts, tutorials, videos, but each is a bit different.
Now you need to reverse engineer every advice to see what version of Angular it was written for, how updated it is, and whether it fits the current way of doing things.

What if you knew the Angular Way of doing things?
Imagine knocking down your tasks and spending your brain cycles on your product’s core.
Wouldn’t it be nice to know Angular like a second language?

You can write modern, clean and future-ready Angular right now.
Sign up below and get more of these helpful posts, free!
Always up to date and I’ve already done all the research for you.

And be the first the hear about my Modern Angular 1.x book – writing future proof Angular right now.

Subscribe to get the latest about modern Angular 1.x

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!


You want to do Angular the right way.
You hate spending time working on a project, only to find it’s completely wrong a month later.
But, as you try to get things right, you end up staring at the blinking cursor in your IDE, not sure what to type.
Every line of code you write means making decisions, and it’s paralyzing.

You look at blog posts, tutorials, videos, but each is a bit different.
Now you need to reverse engineer every advice to see what version of Angular it was written for, how updated it is, and whether it fits the current way of doing things.

What if you knew the Angular Way of doing things?
Imagine knocking down your tasks and spending your brain cycles on your product’s core.
Wouldn’t it be nice to know Angular like a second language?

You can write modern, clean and future-ready Angular right now.
Sign up below and get more of these helpful posts, free!
Always up to date and I’ve already done all the research for you.

And be the first the hear about my Modern Angular 1.x book – writing future proof Angular right now.

Subscribe to get the latest about modern Angular 1.x

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!


You want to do Angular the right way.
You hate spending time working on a project, only to find it’s completely wrong a month later.
But, as you try to get things right, you end up staring at the blinking cursor in your IDE, not sure what to type.
Every line of code you write means making decisions, and it’s paralyzing.

You look at blog posts, tutorials, videos, but each is a bit different.
Now you need to reverse engineer every advice to see what version of Angular it was written for, how updated it is, and whether it fits the current way of doing things.

What if you knew the Angular Way of doing things?
Imagine knocking down your tasks and spending your brain cycles on your product’s core.
Wouldn’t it be nice to know Angular like a second language?

You can write modern, clean and future-ready Angular right now.
Sign up below and get more of these helpful posts, free!
Always up to date and I’ve already done all the research for you.

And be the first the hear about my Modern Angular 1.x book – writing future proof Angular right now.

Subscribe to get the latest about modern Angular 1.x

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.


You want to do Angular the right way.
You hate spending time working on a project, only to find it’s completely wrong a month later.
But, as you try to get things right, you end up staring at the blinking cursor in your IDE, not sure what to type.
Every line of code you write means making decisions, and it’s paralyzing.

You look at blog posts, tutorials, videos, but each is a bit different.
Now you need to reverse engineer every advice to see what version of Angular it was written for, how updated it is, and whether it fits the current way of doing things.

What if you knew the Angular Way of doing things?
Imagine knocking down your tasks and spending your brain cycles on your product’s core.
Wouldn’t it be nice to know Angular like a second language?

You can write modern, clean and future-ready Angular right now.
Sign up below and get more of these helpful posts, free!
Always up to date and I’ve already done all the research for you.

And be the first the hear about my Modern Angular 1.x book – writing future proof Angular right now.

Subscribe to get the next part about testing components and stay updated with the latest about modern Angular 1.x

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!


You want to do Angular the right way.
You hate spending time working on a project, only to find it’s completely wrong a month later.
But, as you try to get things right, you end up staring at the blinking cursor in your IDE, not sure what to type.
Every line of code you write means making decisions, and it’s paralyzing.

You look at blog posts, tutorials, videos, but each is a bit different.
Now you need to reverse engineer every advice to see what version of Angular it was written for, how updated it is, and whether it fits the current way of doing things.

What if you knew the Angular Way of doing things?
Imagine knocking down your tasks and spending your brain cycles on your product’s core.
Wouldn’t it be nice to know Angular like a second language?

You can write modern, clean and future-ready Angular right now.
Sign up below and get more of these helpful posts, free!
Always up to date and I’ve already done all the research for you.

And be the first the hear about my Modern Angular 1.x book – writing future proof Angular right now.

Subscribe to get the latest about modern Angular 1.x

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.

Quick aside: If you’d like to keep getting posts about the latest and greatest in Angular 1.x, and especially hear about one-way data flow, subscribe to my newsletter:

Subscribe to get the latest about modern Angular 1.x

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.


You want to do Angular the right way.
You hate spending time working on a project, only to find it’s completely wrong a month later.
But, as you try to get things right, you end up staring at the blinking cursor in your IDE, not sure what to type.
Every line of code you write means making decisions, and it’s paralyzing.

You look at blog posts, tutorials, videos, but each is a bit different.
Now you need to reverse engineer every advice to see what version of Angular it was written for, how updated it is, and whether it fits the current way of doing things.

What if you knew the Angular Way of doing things?
Imagine knocking down your tasks and spending your brain cycles on your product’s core.
Wouldn’t it be nice to know Angular like a second language?

You can write modern, clean and future-ready Angular right now.
Sign up below and get more of these helpful posts, free!
Always up to date and I’ve already done all the research for you.

And be the first the hear about my Modern Angular 1.x book – writing future proof Angular right now.

Subscribe to get the latest about modern Angular 1.x

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.


You want to do Angular the right way.
You hate spending time working on a project, only to find it’s completely wrong a month later.
But, as you try to get things right, you end up staring at the blinking cursor in your IDE, not sure what to type.
Every line of code you write means making decisions, and it’s paralyzing.

You look at blog posts, tutorials, videos, but each is a bit different.
Now you need to reverse engineer every advice to see what version of Angular it was written for, how updated it is, and whether it fits the current way of doing things.

What if you knew the Angular Way of doing things?
Imagine knocking down your tasks and spending your brain cycles on your product’s core.
Wouldn’t it be nice to know Angular like a second language?

You can write modern, clean and future-ready Angular right now.
Sign up below and get more of these helpful posts, free!
Always up to date and I’ve already done all the research for you.

And be the first the hear about my Modern Angular 1.x book – writing future proof Angular right now.

Subscribe to get the latest about modern Angular 1.x

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.


You want to do Angular the right way.
You hate spending time working on a project, only to find it’s completely wrong a month later.
But, as you try to get things right, you end up staring at the blinking cursor in your IDE, not sure what to type.
Every line of code you write means making decisions, and it’s paralyzing.

You look at blog posts, tutorials, videos, but each is a bit different.
Now you need to reverse engineer every advice to see what version of Angular it was written for, how updated it is, and whether it fits the current way of doing things.

What if you knew the Angular Way of doing things?
Imagine knocking down your tasks and spending your brain cycles on your product’s core.
Wouldn’t it be nice to know Angular like a second language?

You can write modern, clean and future-ready Angular right now.
Sign up below and get more of these helpful posts, free!
Always up to date and I’ve already done all the research for you.

And be the first the hear about my Modern Angular 1.x book – writing future proof Angular right now.

Subscribe to get the latest about modern Angular 1.x

Advanced Angular 1.x: Component Communication with Require

| Comments

Angular 1.5’s components have made scope isolation the default, and rightly so. But, it does mean that inter-component communication requires more thought to get right.

Angular’s require mechanism provides a good way to allow some forms of components communication, especially across a suite of related components.

What does require let you do?
When should you use it?
Why it’s not the right tool for everything?
Keep reading!

How require works?

The require mechanism is an old one, and has been in use quite a lot for advanced Angular directive communication.

Prior to components, you’d use require in order to allow a directive access to a different directive’s controller. That allows directives to expose APIs between one another.

A directive can require the existence of another specific directive, either on its own element or on one of its parent elements.

An example of a same-element kind of communication require is used for, is adding your own validation directive to an input element, and accessing that input’s ngModelController in order to modify the validators.

Accessing parent controllers is more useful for suites of interacting components, such as the way Angular’s form validation works. Every input element in the form can notify the form that it has become valid, invalid, dirty, etc. by optionally requiring a parent ngForm controller and updating it of changes.

As you can see, require is a very powerful mechanism and an inherent part of Angular, that you can use to make your own components cleaner.

When should or shouldn’t you use require?

First and foremost, require doesn’t work in all scenarios. It can only be used by a component/directive to get access to a parent controller (or a controller on the same element). Sibling components can’t communicate using it, and neither can a parent component access its children using it (at least not directly, keep reading for an interesting option).

Another limitation of require is that it assumes the child component knows the name of the other component that it want to require. There’s no abstraction/indirection here – the name of the required component is hard-coded in the requiring component.

Also, I wouldn’t rush to use require to replace any kind of simple binding. It’s totally fine to pass some values between components using bindings–it can be more explicit and simpler to maintain. After all, it’s usually easier to understand what a component depends on if all you need to do is look at its bindings.

Require shines when it allows you setup a family of interacting components, and exposing a rich interface between them without having to wire up half a dozen bindings across multiple layers of components.

Real require example deep-dive: Angular’s forms

As already mentioned, Angular’s whole form and validations mechanism makes heavy use of require.

When you create a <form> in Angular, every element inside it that uses ng-model, such as <input>s, <select>s, etc. registers itself as a control inside that form.

You can see here in the source of ngModel how it optionally requires the form directive. In case a parent form directive exists, ngModelController uses the form directive’s controller and registers as a control. See here.

The form directive, in turn, keeps a list of all these controls and updates them on changes such as $setPristine and $setUntouched.

Notice that while there’s no direct way to access a child component from a parent component, the Angular core team did it here by using require from the child and registering it in the parent, exposing the child controllers to the parent.

Angular’s forms, in turn, have the ability to be nested inside other forms. This happens by optionally requiring a parent form controller. If require does find another parent form directive, the nested form registers in it to let the parent form know it has nested forms.

This is an excellent example of setting up a component architecture, where our components know about one another and use that knowledge to their advantage.

Real talk: How do you use require in your components

Let’s say that we’ve got this structure in our application:

1
2
3
<parent>
  <child></child>
</parent>

And we want to allow the child component to access parent component’s controller.

We’ll add a require block in child’s component definition, and then be able to access the controller inside the controller, like so:

1
2
3
4
5
6
7
8
9
10
11
app.component('child', {
  require: {
    parentCtrl: '^^parent'
  },
  controller: function() {
    var self = this;
    this.$onInit = function() {
      self.parentCtrl.someControllerFunc();
    };
  }
});

What do we have here? The require object allows us to pass as many required component as we’d like. parentCtrl is the name the required controller will be bound as in our component’s controller. ^^parent might seem live a bit of voodoo, but basically we’re saying that we require a parent component called parent to exist.

The ^^ prefix means the component has to be a parent. There’s also the ^, which means we can use a component that’s either a parent or on the current element. And if you simply provide the name, e.g. fooCtrl: 'foo' it means you expect the foo directive to exist on the current element–it will not be searched for anywhere else.

When we’re talking about components, and not directives, you almost always want ^^, though you can use just ^ if you don’t really want to make sure you’re not accidentally requiring the current element.

After we require a component, we can access it from our controller with the name we provided, e.g. this.parentCtrl. I prefer to make sure the name still uses the original component’s name, to be explicit and make maintenance easier.

If the require string is written like we saw above, it means the component is strictly required. Angular will error out if it can’t find the component we asked for. In cases where a component can operate without that required component, you can set the requirement as optional:

1
2
3
require: {
  parentCtrl: '?^^parent'
}

The question mark means that in case Angular can’t find a parent component with that name it will silently ignore it. If you’ll try to access this.parentCtrl you’ll see it’s just nulled.

With great require comes great responsibility

Require is an advanced Angular technique that can really boost certain parts of your app. It’s great for exactly those few highly-interactive components you need to write.

But, require surely shouldn’t be your default or go-to solution for all communication. Start by using regular one-way (<) and expression (&) bindings, and reach for require when it’s required (pun slightly intended).


You want to do Angular the right way.
You hate spending time working on a project, only to find it’s completely wrong a month later.
But, as you try to get things right, you end up staring at the blinking cursor in your IDE, not sure what to type.
Every line of code you write means making decisions, and it’s paralyzing.

You look at blog posts, tutorials, videos, but each is a bit different.
Now you need to reverse engineer every advice to see what version of Angular it was written for, how updated it is, and whether it fits the current way of doing things.

What if you knew the Angular Way of doing things?
Imagine knocking down your tasks and spending your brain cycles on your product’s core.
Wouldn’t it be nice to know Angular like a second language?

You can write modern, clean and future-ready Angular right now.
Sign up below and get more of these helpful posts, free!
Always up to date and I’ve already done all the research for you.

And be the first the hear about my Modern Angular 1.x book – writing future proof Angular right now.

Subscribe to get the latest about modern Angular 1.x

Spotting Outdated Angular 1.x Posts

| Comments

As Angular is maturing, it gets harder and harder for newcomers to make sense of the abundance of materials you find online. I’m pretty sure that at this point, the vast majority of Angular 1.x tutorials use outdated Angular practices–things that modern Angular 1.x projects should not be using.

In order to make it easier for everyone, I decided to grab a list of things that should indicate to you that the post you’re reading might be a bit… stale.

Using $http’s deprecated .success and .error methods

Originally, Angular’s $http service would return promises that had a couple of extra methods on them. While regular promises just have .then (and the sugar-syntax .catch and .finally), those returned from $http also had special .success and .error that weren’t standard and didn’t behave like regular promise callbacks.

I think this was done in order to make things easier for new comers to Angular that also didn’t know much about promises, but we’ve come a long way since then.

These were deprecated quite some time ago, and are completely gone in Angular 1.6.

I ranted about these more in depth here.

ng-controller and standalone controllers

Ever since the announcement that controllers are being killed in Angular 2, the community has been moving off of using standalone controllers. By “standalone” controllers I mean controllers that are used without an encompassing directive/component, e.g. using ng-controller or in a ui-router definition.

ng-controller is used quite a bit in blog posts since it makes things shorter which is helpful. The problem is that developers then go their projects and use what they saw in the examples, not knowing that ng-controller belongs to the past.

Quick aside: If you’d like to keep getting posts about the latest and greatest in Angular 1.x, subscribe to my newsletter:

Subscribe to get the latest about modern Angular 1.x

Using $scope bindings and not using controller-as syntax

Controller-as syntax was introduced in Angular 1.3 and has since become the de-facto standard for writing directives/components in Angular.

Prior to controller-as we would slap everything on the $scope, e.g. $scope.model = {name: ''} and then use the scope directly from our template:

1
<input ng-model="model.name">

This, again, makes things shorter requires less typing, but it is not the way we write proper Angular now.

With controller-as we’d initialize the controller code like so this.model = {name: ''}, and the template would be changed appropriately to not access $scope directly:

1
<input ng-model="$ctrl.mode.name">

Note that I’m using $ctrl as my controller-as name, which is the default for components in Angular 1.5. You might see vm used a lot in blog posts. That’s fine, though I’d recommend just going with the default.

Using non-isolated scopes

This is another thing that was used a lot more in the standalone controller days. Controllers by themselves never have isolated scopes, it’s up to the directive/component to isolate the controller it’s encompassing.

So whenever you used ng-controller, or didn’t specify explicitly that you want your scope to be isolated in the directive definition, you’d instead get a scope that prototypically inherits from its parent scope.

This would quickly become a non-maintainable soup of properties where refactoring is almost impossible without breaking something, somewhere.

That is why for quite some time now the rule of thumb has been to write maintainable, isolated directives.

Using directives instead of components

Since Angular 1.5 was released, introducing components, about 99% of your directives should be written using components.

Essentially, any directive that has its own template should be written as a component. So, ng-click-use a directive, anything else–components.

Yeah, most online material hasn’t been updated to use components whenever appropriate (heck, I’ve got a bunch of posts that need updating as well). But, modern Angular 1.x is components based. Do it.

I’ve written about components at length here.

Two-way binding instead of one-way binding

Another nicety introduced in 1.5 is one-way binding (not to be confused with one-time binding).

One-way binding, like components, what you almost always want to be using. It’s more explicit, more performant and more modern.

Even though it’s a rare occurrence in most blog posts, that doesn’t mean you shouldn’t be using it. It is great, and you should.

Read all about it here.

Using $watch where $onChanges would suffice

It has been common practice to stay clear of $watch when possible. And yet, going through some guides you’d think it has to be used way more often that it really does.

Ever since 1.5 introduced lifecycle hooks in components, we no longer need to use $watch to trigger some logic whenever a binding changes from a parent component.

Instead, use the $onChanges hook to perform whatever is needed without adding an extra watch, and maybe even saving you the need to inject $scope at all.

Read all about the hooks here.

———

I hope this helps you evaluate the freshness of information and understand that just because something doesn’t come up in some posts it doesn’t mean it’s not not popular – just too new to be popular in posts :)


You want to do Angular the right way.
You hate spending time working on a project, only to find it’s completely wrong a month later.
But, as you try to get things right, you end up staring at the blinking cursor in your IDE, not sure what to type.
Every line of code you write means making decisions, and it’s paralyzing.

You look at blog posts, tutorials, videos, but each is a bit different.
Now you need to reverse engineer every advice to see what version of Angular it was written for, how updated it is, and whether it fits the current way of doing things.

What if you knew the Angular Way of doing things?
Imagine knocking down your tasks and spending your brain cycles on your product’s core.
Wouldn’t it be nice to know Angular like a second language?

You can write modern, clean and future-ready Angular right now.
Sign up below and get more of these helpful posts, free!
Always up to date and I’ve already done all the research for you.

And be the first the hear about my Modern Angular 1.x book – writing future proof Angular right now.

Subscribe to get the latest about modern Angular 1.x