Mastering Web Application

(Rick Simeone) #1
Chapter 8

The template uses an array called pages and a number of helper functions, such
as selectPage() and noNext(). These are internal to the implementation of the
widget. They need to be placed on a scope for the template to access them but they
should not appear on the scope where the widget is used. To achieve this we can ask
the compiler to create a new isolated scope for our template.


Isolating our directive from its parent scope


We do not know what the scope will contain at the point where our directive is used.
It is a good practice, therefore, to provide our directive with a well-defined public
facing interface. This ensures that the directive cannot rely on or be affected by
arbitrary properties on the scope where it is used.


We have three options for the scope to be used in our directive and its template. This
is defined in the directive definition:



  • To reuse the scope, from the place where the widget is used. This is the
    default and corresponds to scope: false.

  • To create a child scope, which prototypically inherits from the scope where
    the widget is used. You specify this with scope: true.

  • To create an isolated scope, which does not prototypically inherit, so that it is
    completely isolated from its parent. You specify this by passing an object to
    the scope property: scope: { ... }.


We want to completely decouple our widget's template from the rest of the
application, so that there is no danger of data leaking between the two. We
will use isolated scope as shown in the following image:


Parent
Scope

Child
Scope

Isolated
Scope

Widgetdirective

prototype $Parent

Parent
Scope

$Parent
Free download pdf