I'm so green at Angular, I'm not even sure I've been structuring a search for this correctly. The whole directive and service terminology is still confusing me some, but that isn't my question.
I've read this excellent article series front to back: http://www.ng-newsletter.com/posts/beginner2expert-how_to_start.html
Which is why I am at this point in my application. And why I know my question relates more to the relationship between services and controllers. Rather than syntax-related.
So here is an overview of the app:
I have one controller. This goes off and gets a bunch of farm data for the user using an AJAX call to a PHP file, and displays it on screen using it's own $scope.
var masterApp = angular.module('masterApp', ['myFilters','commonControls']);
masterApp.controller('MasterCtrl', ['$scope','$http', '$filter', 'commonFarmSelector',
function($scope, $http, $filter, commonFarmSelector){
...
$scope.masterCtrl.loadFarmData = function(farmId) {
var postdata = {
"farmId":farmId
};
$http.post('/service/farmproduction', postdata).success(function (data) {
// Do stuff with the $scope using data
}
}
$scope.masterCtrl.loadFarms();
}
You will see I am injecting something called "commonControls". This was a module I created to hold controls that will be reused by multiple controllers. In this case, a dropdown field that contains a list of farms the user has access to (also obtained by an AJAX call):
var commonControlsApp = angular.module('commonControls', []);
commonControlsApp.controller('farmSelectorCtrl', ['$scope', '$http',function($scope, $http) {
$scope.farmSelectorCtrl ={}
// Change entire farm view when a different farm is selected
$scope.farmSelectorCtrl.switchUserFarm = function() {
var farmId = $scope.farmSelectorCtrl.selectedUserFarm;
$scope.masterCtrl.loadFarms(farmId); // !!! Direct link to masterCtrl
};
// Get a list of the user's farms
$http.post('/service/userfarms').success(function (data) {
$scope.farmSelectorCtrl.userFarms = data.getFarmsPerUserResult.farmIds;
});
}]);
This works fine. But as you can see, the farmSelector is directly linked to masterCtrl. And the behavior of that loadFarmData function is specific to that controller. In other words, it will only do things that apply to that page.
The thing is, this farmSelector will be used on other pages. And the precise behavior of a change event will be different for each page. So I am struggling to work out where this behavior should sit. And how it would be called dependent on the controller using the farmSelector.
The article I have linked above suggests this farmSelector should be in a service so it can be reused elsewhere. But I am still confused over how you could give a generic service a specific action to take when an event is triggered.