Angular Best Practices: Communicating Between Components

Joe-EamesWelcome to Part 5 of this review of the Pluralsight course Angular Best Practices by Joe Eames.

Joe has worked both full and part time as a technical teacher for over ten years.

He has produced 18 courses for Pluralsight.

Communicating Between Components

This module compares three different ways of communicating between components.

Communicating with Inherited Scopes

Here we have a parent scope and two child scopes. Joe demonstrates this using a class registration page.

At 5 minutes 20 seconds into the video, Joe analyzes the code. It’s easy to access functionality from child scopes, but there are some drawbacks.
We need to add code to the parent scope and we could end up putting to much on it as the application grows.
We also have logic in our Catalog controller, which has nothing to do with the schedule.
We can also get too many dependencies in our controller this way, making it hard to maintain and reuse.

Communicating with Events

There are two ways to raise an event in Angular:

1. Call scope.$broadcast to raise the event on the originating scope and send it down to child scopes
2. Call scope.$emit to raise the event on the originating scope and sends it up the scope chain.

To broadcast events call $broadcast on the rootscope which sends it down to all child scopes.

At 1:30 Joe shows how to change the Inherited Scopes example to work with events instead.
We can refactor the code so that the schedule is no longer part of the Catalog controller.

At 4:25 Joe analyzes the code, noting the logic in each controller is now related to the controller.
Drawbacks include needing to being in the $rootscope as a dependency, the fact that events are a form of global, and the need to use a string for the event name.

Communicating with Services

Services are singletons

Joe discusses the benefits and drawbacks 4 minutes in.

The biggest benefits is no business logic in controllers.
Disadvantages include the fact that it requires more setup work, and it can feel artificial to put things in a service just so we can get two different scopes to communicate.

Joe says they win out over the other methods for long-term maintenance, but can be overkill for simple code.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s