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