While creating dashboard application I came to situation where I need to have both AngularJS
controller and service in one.
At main (1st) page I have mainController
(nothing with layout) and also layoutController
which is binded to the buttons with methods loadLayoutFromAPI()
and saveLayoutToAPI()
.
Now, at secondary (2nd) there is secondController
only and not layoutController
. I need to use methods from the layoutController
directly from secondController
and I prefer not to insert ng-controller
directive inside the HTML (instead put it to secondController
through dependency-injection like service).
MainPage (1st):
<div ng-controller="mainController">
<!-- some other code -->
<div ng-controller="layoutController as ctrl">
<a href="#" ng-click="ctrl.loadLayoutFromAPI()">Load</a>
<a href="#" ng-click="ctrl.saveLayoutToAPI()">Save</a>
</div>
</div>
SecondaryPage (2nd):
<div ng-controller="secondController">
<!-- some other code -->
</div>
I tried to look for this issue, but no answers found at all.
Question: How should I use same piece of code (methods save()
and load()
) once as a Controller (ng-controller
) and other time as a service (included via dependency-injection
)?
Thanks
JS Bin as requested
Don't use methods from other controllers directly from other controllers... this is why services are there. Controllers are only there to engage with the view!
If you want to communicate between controllers, or directives or anything else that is what services, factories and providers are for. When building any application, you always abstract out common functionality to some kind of service
For example:
//Just an APP def
var app = angular.module('dashApp', []);
//LayoutController
app
.controller('layoutController', ['CtrlService', function(ctrlService){
this.saveLayoutToAPI = function(){
ctrlService.save();
}
this.loadLayoutFromAPI = function(){
ctrlService.load();
}
}]);
//Main Controller
app
.controller('mainController', function(){
//no work with layout at all
});
//Secondary controller
app
.controller('secondController', ['CtrlService', function(ctrlService){
this.save = function(){
ctrlService.save();
}
this.load = function(){
ctrlService.load();
}
}]);
app
.service('CtrlService', function () {
var obj = {
save: function () {
console.log('Layout saved.');
},
load: function () {
console.log('Layout loaded.');
}
}
this.save = obj.save;
this.load = obj.load;
});