How can I run function in two separated controllers in angularjs

29 Views Asked by At

I have two separate angularjs controllers that are named HomeController and SearchController.

I have a function that named Search() in HomeController.

How can I run search function from searchController?

2

There are 2 best solutions below

0
Azad On

define the 'search' function in a factory, inject that factory into both controllers then you can access 'search' function from both controllers.

sample:

app.controller('HomeController', function(searchFactory){
   //calling factory function
   //searchFactory.search();

});

app.controller('searchController ', function(searchFactory){

   //calling factory function
   //searchFactory.search();

});

app.factory('searchFacotry', function(){
  return{
    search: function(arg){
      alert('hello world');
    };
  };
});
2
Gaurav On

I have made this Plunker which does the above. The app.js file looks like this. It uses a factory declaration. Alternatively if you just want this function to store and return some data then you can use $rootScope service of angular, it is accessible globally. Services are prefered when they are performing some operation. Take a look at this Link which have answers explaining the use of services vs rootScope.

app.controller('HomeCtrl', function($scope, searchService) {
$scope.ctrl1Fun= function() {
    searchService.search();
}
});

app.controller('SearchCtrl', function($scope, searchService) {
      $scope.ctrl2Fun= function() {
       searchService.search();
      }
})

app.factory('searchService', function(){
  function search(){
    alert('hello World')
  }
  var service = {search : search}
  return service
});