Learn how to use directive scope variables and access them from your directive controller

Angular directives can have a separate, isolated scope, which is even the suggested approach most of the time. And they can have directive controllers. But…how do I access the directive’s scope variables from the directive controller and vice-versa?? It’s quite simple, read on and see it yourself.

This article is part of my "Learning NG" series, presenting some of my adventures while learning Angular. Check out the series intro and other articles. Something not quite as you think? I'm more than happy for any kind of feedback and improvement suggestions.

I’m having an isolated directive which has some scope properties defined on it. Here’s a dummy example:

As can be seen, we can directly refer to the scope variables from the directive’s template.

But what about if I have a directive controller and within that controller I’d like to use the variable defined on the directive scope to invoke some service and finally display the result from that service call onto the directive’s template?? Do I have access to the directive’s scope variables from within a directive controller?

As you can see, I use the $scope to get access to the directive variable. Similarly, I can access a controller’s scope variables through the proper “controller as” variable name, in my example vm:

app.directive('myDirective',function(){return{restrict:'E',scope:{directivevariable:'='},template:'Hi, {{ directivevariable }}. And I am from the controller: {{ vm.controllerVariable}}.',controller:function($scope,externalService){varvm=this;// accessing the directive's scope variableexternalService.doSomethingUseful($scope.directivevariable);vm.controllerVariable='hi from the controller';},controllerAs:'vm'}});

Here’s a Plunker example that illustrates some scenarios:

Update: bindToController in Angular 1.4

Angular v1.4.x introduced the bindToController option which allows to have variables passed to a directive to be bound directly to the corresponding directive controller instance. As such, we can get rid of $scope, which is the suggested practice for moving on towards Angular 2.0.