Understanding Inter-Control Operations in angularJS

Asked 2 years ago, Updated 2 years ago, 149 views

I would like to use angularJS to perform certain actions from one controller in another controller. Is there a way?

Example
HTML side
ng-click to call sampleA() on controller A

On the JSide
Run controller B's sampleB() from controller A's sampleA

angularjs

2022-09-30 21:25

1 Answers

$rootScope to $broadcast to send events to the descendants of $rootScope, that is, all scope.

DEMO

myApp.controller('A',['$scope','$rootScope', function($scope,$rootScope){
  $scope.sampleA=function(){
    $rootScope.$broadcast('myevent');
  };
}]);
myApp.controller('B', ['$scope', function($scope){
  $scope.$on('myevent', function(event,...args){
    $scope.sampleB();
  });
  $scope.sampleB=function(){
    // do something
  }
}]);

Reference
https://stackoverflow.com/questions/19446755/on-and-broadcast-in-angular


2022-09-30 21:25

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.