Search code examples
angularjsangularjs-directiveangularjs-scopeangularjs-controlleras

Shared scope of a directive when 'controller as' syntax is used


Here is a simple example of using directives (adapted from the official guide) - JSFiddle

<div ng-controller="Controller">
  <my-customer></my-customer>
</div>


angular.module('my-module', [])
.controller('Controller', function($scope) {
     $scope.vojta = { name: 'Vojta', address: '3456 Somewhere Else' };
 })
.directive('myCustomer', function() {
     return {
        restrict: 'E',
        template: 'Name: {{vojta.name}} Address: {{vojta.address}}'
     }
 });

The above directive has the same scope as its parent controller. How can I do the same with controller as syntax?

It's possible to do this with isolated scopes, but I am looking for a solution where you don't create a separate scope for the directive. Is it simply possible?

I tried everything from controllerAs, bindToController and require: '^ngController' without any success.


Solution

  • For the controllerAs syntax, in your controller create a ViewModel object having the reference to this as follows:

    var vm = this;
    vm.vojta = { name: 'Vojta', address: '3456 Somewhere Else' }; //your object
    

    And in the template, you have to use the as to give an alias to your controller as follows:

    <div ng-controller="Controller as ctrl"> //now inside this scope use 'ctrl' which acts as the 'scope' of the controller.
      <my-customer></my-customer>
    </div>
    

    In your directive:

    template: 'Name: {{ctrl.vojta.name}} Address: {{ctrl.vojta.address}}' //notice the use of 'ctrl'
    

    Working fiddle here.