1

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?

1
  • You can broadcast from controller and listen it on directive Commented Oct 2, 2015 at 7:28

1 Answer 1

4

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

    }
  };
}]);
Sign up to request clarification or add additional context in comments.

1 Comment

It works, thanks! I've updated my Plunk.

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.