2

it seems that there are some questions online with similar matters but no solution worked for me.

I'm having a directive, let's say that includes a function like this (within the directive):

link: function(scope, element, attrs) {

     scope.myfunction = function (){
          console.log('function run');
     };
}

Witch i want to make it run (call it) from a controller with something simple like this:

$scope.myFunction();

So i can call it from a part of my page outside the directive code let's say like this:

<button ng-click="myFunction()">Run</button>

Is it possible?

Vassilis Pits
  • 3,788
  • 4
  • 33
  • 48
  • 1
    You could share the scope instance rather than creating a new one as I assume you are doing, or you could move the function into a service and inject that both in the directive and your controller? There is probably a better way to design this but it is hard to tell without any context of why you are trying to do this – Sebastian Piu Sep 08 '15 at 08:35
  • Seems to be a duplicate of http://stackoverflow.com/q/21202670/5052704 See if this helps. – Vipul Agarwal Sep 08 '15 at 08:35
  • See http://stackoverflow.com/q/14883476/1099240 – Dmitry Frank Sep 08 '15 at 08:36
  • No both answers doesn't work for me. Well second one is a different approach that it's not good for what i'm doing. – Vassilis Pits Sep 08 '15 at 08:40
  • do you wanted to call the directive method from outer controller? – Pankaj Parkar Sep 08 '15 at 09:01

1 Answers1

6

Finally i got the solution by broadcasting scope like this.

In controller:

$scope.startFunction = function(){
    $scope.$broadcast('startfunction');
};

In directive:

scope.$on('startfunction', function () {
     console.log('function run');
});
Vassilis Pits
  • 3,788
  • 4
  • 33
  • 48
  • If view is already loaded then brodcast wont get called for second time. any suggestion? – Sopo May 24 '18 at 10:19