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?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
S BOT
  • 13
  • 4

2 Answers2

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');
    };
  };
});
Azad
  • 5,144
  • 4
  • 28
  • 56
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
});
Community
  • 1
  • 1
Gaurav
  • 609
  • 8
  • 20
  • I Want run function that is in HomeController – S BOT Dec 12 '16 at 18:41
  • 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. – Gaurav Dec 12 '16 at 18:45