angularjscontrolleras

Access this of a controller when using controller as inside directive template


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";
});

Solution

  • 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) {
        }
      }
    });