0

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

1 Answer 1

0

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>

Sign up to request clarification or add additional context in comments.

6 Comments

I've tried adding self = this, self.test = 'TEST' to the controller and using ctrl.test to the directive, but it still returns undefined
please compile your codes with this sample, and see what different between them
The only differences are the controller name and directive name
add ctrl in last of link function as argument in your directive
i change it as your sample!
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.