I have two pages and two controllers that perform searches on the same dataset. One has a simple form to specify search criteria. The other allows the user to select data on a map (by selecting an area or clicking on features on the map).
The result of the search is then displayed on a data table below the search controls (on the same page).
So, the controllers have different search features, but also share a lot of common behaviour, i.e. displaying the grid, paging, reloading, batch edition of data from the grid etc.
As a result, there are several functions that are repeated, sometimes with slight variations, sometimes exactly identical, in both controllers.
The part of the page that displays the data is also a shared template, included with ng-include
on both search pages.
Here is an example :
$scope.selectAllRows = function(){
var selectedItems = $scope.searchState.selectedItems;
angular.forEach($scope.searchState.searchResult.rows, function(row){
// add only if not already selected
if(selectedItems.indexOf(row) < 0){
selectedItems.push(row);
}
});
};
This function selects all the rows in the table. It is bound to the ng-click
of a button on the page.
There are many other functions like this, that basically read some state from the $scope
, perform some logic, and place something new back to the $scope
.
I would like to remove the duplication of these functions and regroup the common behaviour in a single unit of code.
Note : what I am trying to share here is behaviour, not data. These functions will perform the same logic, but on different scopes.
Since these are really presentation / UI stuff, and need to be put on the $scope
, I don't think a service could be used because the $scope
is a strictly controller thing and cannot be injected into services.
I am experimenting with defining a standalone function, in a different file, and calling this function from both controller :
myapp.defineCommonControllerBehaviour = function($scope, someOtherService){
$scope.selectAlRows = function(){....}
$scope.someOtherCommonTask = function(){
someOtherService.doTheTask();
}
//etc...
};
//controller 1
myapp.defineCommonBehaviour($scope, someOtherService);
//controller 2
myapp.defineCommonBehaviour($scope, someOtherService);
It works but is not very elegant, since it defines a function in the global scope, outside of any Angular module.
Is there a angular native way of achieving this ? Or at least more in line with the Angular architecture ?