nick.cook
nick.cook

Reputation: 2141

AngularJS Custom directives - Issue accessing controllerAs variables/objects in directive link

I've just started refactoring my code to do DOM manipulation and functions in directives instead of inside controllers as I had previously been doing, but I'm having issues accessing variables/objects defined using controllerAs 'this' syntax within the controller from which I need them to be inherited.

I've tried using bindToController as below, where I've added the different objects that are used in the directive function, but when I try to access these withink the 'link', they're all returning as undefined in the console.

Example here. 'this.test' defined in controller, tried accessing this in the directive in a console log message.

Controller:

app.controller('notificationsController', function($scope, $state, $http, $document, $mdDialog, $filter, $timeout, $mdToast) {

  this.test = 'TEST';

Directive:

app.directive('clearNotifications', function($mdDialog, $mdToast, $timeout) {
return {
    controller: 'notificationsController', 
    controllerAs: 'notifications',
    scope: {},
    bindToController: {
        notifications: '=',
        filters: '=',
        test: '@'
    },
    restrict: 'A',
    link: function(scope, element, attrs) {
        element.bind('click', function() {

            console.log('notifications.test string test: ' + notifications.test);

Upvotes: 0

Views: 37

Answers (1)

Maher
Maher

Reputation: 2547

this in controller is different with controllerAs in directive , in directive you should use ctrl or model to binding.

var app = angular.module("app", []);

app.controller("notificationsController", function($scope) {
  this.test = "foo!";
})

app.directive("clearNotifications", function() {
  return {
    controller: 'notificationsController',
    controllerAs: 'notifications',
    scope: {},
    bindToController: {
      notifications: '=',
      filters: '=',
      test: '@'
    },
    restrict: 'A',
    link: function(scope, element, attrs, ctrl) {
      element.bind('click', function() {
        console.log('notifications.test string test: ' + ctrl.test);
      })
    }
  }
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app">
  <button clear-notifications>clearNotifications</button>
</div>

Upvotes: 0

Related Questions