JSFiddle

It’s possible to access the attribute through the isolate scope also. The following code achieves the same.

JavaScript

JavaScript

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

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

//$scope.lightsStatus = attrs.lightsStatus;

}

};

});

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

});

Note how defining the scope as so is equivalent to reading the attribute directly (although beware of earlier versions of Angular where the parameter passed in may be ‘undefined’ until angular is finished rendering. This annoyance has been rectified in recent versions of Angular).

While both techniques achieve the same, there is a fundamental difference between the two code examples.

Isolate Scope

JavaScript

1

2

3

4

5

/* */

scope:{

lightsStatus:'@'

},

/* */

The above snipped isolates the scope. What this means is that the controller and this directive now have different scopes. Before this, the directive had direct access to the controller scope. Now, it only sees the defined properties.

JSFiddle

Note how the directive simply inherits the lightStatus property of the scope, no further definition of assignation is required.

Pass by value ‘@’

To consolidate the notion of passing the the parameter by value using ‘@’ lets add the following to the controller.

$scope.lightStatus = “dimmed”;

This presents a question. Will the value of lights in the car now be “dimmed” or will it be “lightsStatus”?
Or put differently, are we passing in a reference to a variable ($scope.lightsStatus) or are we simply passing in a string with value “dimmed”?

The answer is simple. We’re passing in a string value, not a reference to variable. This is determined by the fact that the parameter is received in the directive using ‘@’. If we used ‘=‘ then we would be passing a reference to $scope.lightsStatus. This notion is explored in the next tutorial.

Conclusion

This tutorial has examined the concept of passing a value to an angular directive by value using the ‘@’ technique.
JSFiddle code examples demonstrate the key points along the way.