0

I am using angular js as my client side. I want to invoke one function which is in another controller. How can i achieve this?

Pooja K Bhatt
  • 979
  • 2
  • 10
  • 18
  • Possible duplicate of [Can one AngularJS controller call another?](https://stackoverflow.com/questions/9293423/can-one-angularjs-controller-call-another) – Bill P Aug 23 '19 at 09:13

2 Answers2

0

var app = angular.module('MyApplication', []);
app.controller('Controller1', function($scope, $rootScope) {
  $scope.function1 = function() {
    console.log('Controller 1 clicked and Function 1 called');
  }
  //receive the fuction using $on MyFunction
  $rootScope.$on("CallController1", function() {
    console.log('Controller 2 clicked and Controller 1 called');
  });
});
app.controller('Controller2', function($scope) {
  $scope.function2 = function() {
    console.log('Controller 2 clicked and Function 2 called');
    $scope.$emit("CallController1"); //emit the fuction using MyFunction
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<div ng-app="MyApplication">
  <div ng-controller="Controller1">
    <button ng-click="function1()">function 1</button>
  </div>
  <br>
  <div ng-controller="Controller2">
    <button ng-click="function2()">function 2</button>
  </div>
</div>
Parth Raval
  • 4,097
  • 3
  • 23
  • 36
0

Though it can be done by making use of the rootScope but polluting the rootScope is a risky affair taking into consideration the digest and watch cycles that run whenever the state of the application changes at run time.Burdening it more is not recommended. The best and cleanest way to share common code or functionality is to use service/factory and then use it in your respective controller.

For e.g. we can create a shared service like below

angular.factory('sharedList', function() {
var list = [];

return {
  addItem: addItem,
  getList: getList
};

function addItem(item) {
  list.push(item);
}

function getList() {
  return list;
}
});

and include this service in your controllers as

app.controller("MyCtrl", function($scope, sharedList) {
  $scope.users = sharedList.getList();
});

app.controller("AnotherCtrl", function($scope, sharedList) {
  $scope.firstUser = sharedList.getList()[0];
});  

and in case if you want to add something then you can make the code changes likewise.

Hope it helps.