1

How do i access This of controller inside of directive and its template when not using isoloted scope?

app.controller('ChildCtrl', function() {
  this.name = "Name from children";
});
Hacker
  • 7,798
  • 19
  • 84
  • 154

1 Answers1

1

Simple parse it as controller as instance value into your directive scope like in this simple fiddle demo:

View

<div ng-controller="MyCtrl as ctrl">
  Hello, <span simple-directive data="ctrl.name"></span>!
</div>

AngularJS application

var myApp = angular.module('myApp',[]);

myApp.controller('MyCtrl', function ($scope) {
    this.name = 'Superhero';
});

myApp.directive('simpleDirective', function () {
  return {
    restrict: 'A',
    scope: {
      data: '='
    },
    template: '{{ data }}',
    link: function (scope, elem, attrs) {
        console.log(scope.data);
    }
  }
});

An other approach is to just parse your controller into the directive by using controller:'MyCtrl as ctrl' like in this demo fiddle.

View

Hello, <span simple-directive></span>!

AngularJS application

var myApp = angular.module('myApp',[]);

myApp.controller('MyCtrl', function ($scope) {
  this.name = 'Superhero';
});

myApp.directive('simpleDirective', function () {
  return {
    restrict: 'A',
    controller:'MyCtrl as ctrl',
    template: '{{ ctrl.name }}'
  }
});

You can also parse the hole controller instance to in scope and access it like in this demo fiddle.

View

<div ng-controller="MyCtrl as ctrl">
  Hello, <span simple-directive ctrl="ctrl"></span>!
  <br />
  <input type="text" ng-model="ctrl.name">
</div>

AngularJS application

var myApp = angular.module('myApp',[]);

myApp.controller('MyCtrl', function ($scope) {
    this.name = 'Superhero';
});

myApp.directive('simpleDirective', function () {
  return {
    restrict: 'A',
    scope: {
      ctrl: '='
    },
    template: '{{ ctrl.name }}',
    link: function (scope, elem, attrs) {
    }
  }
});
lin
  • 17,956
  • 4
  • 59
  • 83