Search code examples
angularjsangularjs-scope

How to call a method from a controller to another controller in angular js


I have a view for SidebarController like below -

<a ng-click="reachMe($event);$event.preventDefault()" ng-href="#/app/hello">

Before going to the link I want to call reachMe() to check some changes on page and need to show an alert if any changes made

function SidebarController($rootScope, $scope, $state, $location, SidebarLoader){
 $scope.reachMe = function(event){

//here I want to call function isPageChanged() from StaticPageController
//something like this
// if StaticPageController.isPageChanged() return true
// then show alert
// else
// $location.url($href) 
 } 
}

Solution

  • Update 1 : Not sure about this, But give it a try.

    <div ng-app="testApp" ng-controller="ControllerOne">  
    
        <button ng-click="methodA();"> Call Another Controller</button> 
    
    </div> 
    
    
    <script> 
    var app = angular.module('testApp', []); 
    app.controller('ControllerOne', function($scope, $rootScope) { 
      $scope.reachMe = function() {
         var arrayData = [1,2,3]; 
          $rootScope.$emit('callEvent', arrayData); 
    
          if($rootScope.isChanged){
          // Show Alert
          }else{
          //Go to route
          }
    } 
    
    }); 
    app.controller('ControllerTwo', function($scope, $rootScope,$state) { 
      $scope.checkSomethingChanged = function() {
          alert("Hello");
          $rootScope.isChanged = true;
      }
    
      $rootScope.$on('callEvent', function(event, data) { 
        console.log(data);
        $scope.checkSomethingChanged(); 
      });  
    }); 
    

    Following method worked for me perfectly :

    <div ng-app="testApp" ng-controller="ControllerOne">  
    
    <button ng-click="methodA();"> Call Another Controller</button> 
    
    </div> 
    
    
    <script> 
    var app = angular.module('testApp', []); 
    app.controller('ControllerOne', function($scope, $rootScope) { 
      $scope.methodA = function() {
         var arrayData = [1,2,3]; 
          $rootScope.$emit('callEvent', arrayData); 
    } 
    
    }); 
    app.controller('ControllerTwo', function($scope, $rootScope) { 
      $scope.reachMe = function() {
          alert("Hello");
      }
    
      $rootScope.$on('callEvent', function(event, data) { 
        console.log(data);
        $scope.reachMe(); 
      });  
    }); 
    </script>