简体   繁体   中英

AngularJS: Access directive from controller

Background

I have a top level directive which needs to be accessed by a controller. Please consider this Plunk .

Directive

app.directive('topDirective', ['$compile', function($scope){
  return {
    scope: {},
    restrict: 'E',
    template: '<h3>Top Directive</h3><p><button ng-click="CallMe()">Click Me</button></p>',
    controller: function($scope) {
      var self = {};

      $scope.CallMe = function(){
        alert('Call Me');
      };
    },
    link: function($scope, $elem, $attrs, $ctrl) {

    }
  };
}]);

Controller that needs access

app.controller('subController', [
  '$scope', 
      function($scope){
        var self = {};

        $scope.CallDirective = function() {
          alert('>>> Replace by call to directive function CallMe (somehow) <<<')
        };
      }]);

Question

What do I need to do to replace this line:

alert('>>> Replace by call to directive function CallMe (somehow) <<<')

by an actual call to the CallMe() function in the directive?

If not possible directly, is there a way to share functionally that both the directive and controller can use? My first thought would be a service, but it would need to do DOM manipulation in the real scenario, so that's not an option.

Any suggestions?

in Controller emit the event

app.controller('subController', [
  '$scope','$rootScope', 
      function($scope,$rootScope){
        var self = {};

        $scope.CallDirective = function() {
          var data ='This is new data';
          $rootScope.$emit('callDirective',data);
        };
      }]);

and in directive you can do it like

app.directive('topDirective', ['$compile', function($scope){
  return {
    scope: {},
    restrict: 'E',
    template: '<h3>Top Directive</h3><p><button ng-click="CallMe()">Click Me</button></p>',
    controller: function($scope,$rootScope) {
      var self = {};

      $scope.CallMe = function(data){
        alert(data);
      }; 
      $rootScope.$on('callDirective',function(type,data){
         $scope.CallMe(data);
});
    },
    link: function($scope, $elem, $attrs, $ctrl) {

    }
  };
}]);

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