I'm making an app in AngularJs and I'm facing a situation where I need to call the same function in multiple views.
In this case, it's a store system where the same store can be visible in multiple views. In the home, if it's near the user, in a paid ad, in the search result, etc..
I know this function should be in a service, which I already did. But the question is: How should I call this function from the view/html?
I'd like to avoid re-define the same calling over and over in multiple controllers, but until now, didn't found anything related to this specific problem.
This is the code I have:
function mainFactory($http) {
var service = {
addFav: _addFav
};
return service;
function _addFav(data, func) {
return $http.post(baseUrl+func,data).then(
function(res) {return res.data;},
function(err) {alert(_errorMsg);}
);
};
}
function HomeController() {
vm.addFavorites = addFavorites;
function addFavorites(data) {
var func = 'function_name';
mainFactory.addFav(data,func);
}
}
function AdvController() {
vm.addFavorites = addFavorites;
function addFavorites(data) {
var func = 'function_name';
mainFactory.addFav(data,func);
}
}
function SearchController() {
vm.addFavorites = addFavorites;
function addFavorites(data) {
var func = 'function_name';
mainFactory.addFav(data,func);
}
}
As you can see, I need to call the same function in multiple controllers.
I already saw some other examples saying to use this function as a $rootScope function from the .run, but also way more content warning about not being a good practice to define functions as root functions.
Any suggestion on how to solve this?
Edit:
Other solution I'm using right now, is to have a 'MainController' defined in the body tag via directive, so i can use this function in the whole app. But this controller is getting way to complex to maintain, with a lot of functions/process.