0

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 Answers 2

1

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');
    };
  };
});
Sign up to request clarification or add additional context in comments.

Comments

1

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

2 Comments

I Want run function that is in HomeController
If you need to reuse a function written inside a controller, you should take that function out and make it available through a service or share it through shared scope or rootscope. That's the standard practice, it makes your code reusable and less redundant.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.