AngularJS – isolate scope – ‘=’ (pass by reference)


This blog will explore the concept of passing object to angularJS directives / templates using by reference.
When an object is passed by reference both the parent (controller or parent directive) and the child directive/template have access to the object. The relationship is bidirectional.

This tutorial details creating directive/templates in general (without an isolated scope).
This tutorial demonstrates passing values by value to angular directives/templates (@).

As with the ‘by value @’ blog, an analogy of a driver and a car are used. The driver is the controller and the car is the directive/template.

In this ‘by reference’ example, the driver (controller) can turn on and off the lights on the car (directive/template).
Lets have a look at some sample code.




The driver has a button which allows him/her to turn off or on the lights. Note how both the car directive/template and the parent controller (driver) both show the status of the lights. Both hold references to the same object.

Toggling the lights status by clicking the button causes the lights status to update in both locations thus demonstrating the ‘by-reference’ relationship.


To illustrate this further, we’ll now introduce a rain-sensor to the car. When the car detects rain, it will automatically turn on the lights.
I.e. the lightsStatus variable is not only accessible, it is editable by both the parent (driver) and car (child).





The rain-sensor is emulated by the ‘Toggle rain’ button.

Note how this event handler is in the directive/template rather than the parent controller.

When the event handler (i.e. the scope.simulateRain function) sets the status of the lights, the driver sees his indicator change also. The relationship is bi-directional .


The concept of passing objects from parent controllers to directives by reference using ‘=’ has been demonstrated.

The same variable defined in the parent is editable by the child directive to which is was passed. Both the parent (directive or controller in this example) and the child share the variable.