简体   繁体   中英

Can we call the function inside the controller from another controller of another file in AngularJS?

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.

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 .

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