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

Introduction

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.

HTML

AngularJS pass by reference '='

XHTML

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

<div ng-app="app" >

<div ng-controller="ctrl">

<fieldset><legend>Driver (<em>Controller</em>)</legend>

<div class="mb40px">

<button ng-click="toggleLights()">Toggle Lights</button>

Lights: {{lights}}

</div>

<car-template lights-status="lights" ></car-template>

</fieldset>

</div>

</div>

<!-- Angular Template -->

<div id="carTemplate"style="display:none;">

<fieldset><legend>Car (<em>Template</em>)</legend>

Lights: {{lightsStatus}}

</fieldset>

</div>

JavaScript

AngularJS pass by reference '='

JavaScript

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

varngApp=angular.module('app',[]);

ngApp.directive('carTemplate',function(){

return{

scope:{

lightsStatus:'='

},

restrict:"E",

template:document.getElementById('carTemplate').innerHTML,

replace:true,

link:function(scope,elem,attrs){

}

};

});

ngApp.controller('ctrl',function($scope){

$scope.lights="off";

$scope.toggleLights=function(){

$scope.lights=($scope.lights==="on")?"off":"on";

};

});

JSFiddle

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).