1

I am trying to call a function inside a controller which is in another controller inside another js file.

I have tried $broadcast and $emit but I think it works only inside the same file.

I have a controller called videoWidgetController which has the function named clickVideoWidgetListItemFromDOM.

I need to call it from my another controller named videoController.

In this file, I am calling the function on click event like data-ng-click="clickVideoWidgetListItemFromDOM(video, $index)"

videoController

$scope.clickVideoWidgetListItem = function(video, index) {  
    $scope.$emit("myEvent"); *** didn't work for me ***
    $rootScope.$broadcast("myEvent", {video: video,index: index }); *** didn't work for me ***  
};

videoWidgetController

$scope.$on("myEvent", function (event, args) {
    alert(1);
    console.log(args);
   $scope.clickVideoWidgetListItemFromDOM();
});

I was trying as mentioned in this link but, couldn't get the solution.

I searched a lot but unfortunately still in the same problem.

halfer
  • 19,824
  • 17
  • 99
  • 186
Owais Aslam
  • 1,577
  • 1
  • 17
  • 39
  • Why not just factor out the common parts of the two controllers into another file? – Gherman Apr 09 '18 at 14:34
  • $rootScope.$broadcast should definitely work . not sure why it didnt.Do they belong to same module? – sridhar.. Apr 09 '18 at 14:36
  • [`$emit` emits it UP, to parents](https://stackoverflow.com/a/28156845/8495123), which in your case can only be the global scope - `$rootScope`, so you need to transmit it with `$rootScope.$emit("myEvent")` and listen with `$rootScope.$on`. – Aleksey Solovey Apr 09 '18 at 14:46
  • This almost certainly means that your code is poorly structured. Try to take a step back and spilt the code into smaller logical components. – Jakub Judas Apr 09 '18 at 15:38

1 Answers1

0

In order for a broadcast-emit data transfer to happen, the following condition must be satisfied

The event is to be broadcasted from the parent controller, and the event is to be listened from the child controller. Broadcast method id used to transfer data from parent to child.

If this hierarchy does not work, you can transfer data by services.

Nitheesh
  • 19,238
  • 3
  • 22
  • 49