简体   繁体   中英

How to get access to controller function from directive in AngularJS

So, this is my controller with some tiny function:

class DashboardCtrl {
  constructor ($scope, $stateParams) {
    "ngInject";

    this.$scope = $scope;
    this.title = 'Dashboard';
  }
  loadCharts () {
    // some logic here
  }
 }

export default DashboardCtrl;

And now my directive:

class TreeNodeTooltip {
  constructor ($scope, $state) {
    "ngInject";

    this.$scope = $scope;
    this.$state = $state;
    this.scope = {
        loadCharts: '&'
    };
  }
  link (scope, elem, attrs) {
    $(elem).on('click', '.node-name', (e) => {
       console.log(this.$scope.loadCharts());
       console.log(this.scope.loadCharts());
       console.log(this.$scope.main.loadCharts());
    }
  }
}

This is not working, i've tried couple of ways but ... How to get access to controller from directive, to controller function? Thx for help.

I think you are not fully understanding what Angular's .directive() is doing. It is not registering class for directive instances, but it is registering directive factory class .

I guess that TreeNodeTooltip from your question is what you register as the directive factory. In that case $injector can inject services in the constructor, but not any actual $scope (not sure how it is possible you are not getting error from that).

The actual directive instance is being initialized through the postLink / link function. There you also have directive's scope available. However you are accessing scope from the directive definition this.scope and that does not make sense.

The following modification provides a bit sense to the provided code:

class TreeNodeTooltip {
  constructor () {
    this.scope = {
        loadCharts: '&'
    };
  }
  link (scope, elem, attrs) {
    $(elem).on('click', '.node-name', (e) => {
       console.log(scope.loadCharts());
    }
  }
}

And then in the template:

<!-- ngController only required if it is not registered as state controller -->
<div ng-controller="DashboardCtrl as dashboardCtrl">
    <tree-node-tooltip load-charts="dashboardCtrl.loadCharts()" />
</div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM