s.jain
s.jain

Reputation: 23

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) 
 } 
}

Upvotes: 0

Views: 870

Answers (2)

Sangwin Gawande
Sangwin Gawande

Reputation: 8156

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>

Upvotes: 1

Jester
Jester

Reputation: 3317

A controller is not the right concept for sharing functionality. Use a Factory or Service for that.

var logicFactory = function () {
    return {
        methodA: function () {

        },
        methodB: function()
        {
        }
    };
}

You can then inject that factory into each controller where it is needed like:

var ControllerA = function ($scope,logicFactory) {
    $scope.logic = logicFactory;
}

ControllerA.$inject = ['$scope', 'logicFactory'];

Another option is to use the broadcast/emit Patern. But I would use that only where really necessary: Usage of $broadcast(), $emit() And $on() in AngularJS

Upvotes: 1

Related Questions