0

I am new to AngularJS and I am trying to call doSomething() function which is declared inside a directive. Please help me.

This is my directive:

app.directive('myDirective', function() {
    return {
        scope.doSomething = function(parm1, param2) {
        console.log('print This');
    }
});

This is my controller:

function MyCtrl($scope) {
    $rootScope.$broadcast('doSomething', [parm1,'parm2']);
}
Gargaroz
  • 313
  • 9
  • 28

1 Answers1

0

You could solve this by using angularjs $broadcast/$on events. Basically you communicate by broadcasting events which some component will listen on.

To do this, start by adding an event listener in the directive which will listen to events with id 'doSomething'.

app.directive('myDirective', function () {

    var controller = ['$scope', function ($scope) {

          $scope.$on('doSomething', function(e){
                doSomething(e.parm1, e.parm2)
            });
          };

          $scope.doSomething = function(parm1, param2) {
             console.log('print This');
          }
      }],

      template = '<h4>I will listen on your event</h4>

      return {
          controller: controller,
          template: template
      };
  });

Then broadcast the 'doSomething'-event from your controller with the object you want to send

function MyCtrl($scope) {
    var obj = { 'parm1': parm1, 'parm2':parm2 };
    $scope.$broadcast('doSomething', obj);
}

(Note that the directive must be declared in the controller scope, else use rootscope but try to avoid that)

Marcus Höglund
  • 16,172
  • 11
  • 47
  • 69