My idea is to use factory to have in controllers a shared model instance and parent controller to support the most common operations and extend it in children classes.
Ex. var App = angular.module('App', []);Below is shared model with public api.
App.factory('SharedModel', function () {Parent controller
var model = { /* some definition of object */ };
// public API
return {
getValue: function() {
return model.value;
},
updateValue: function(value) {
model.value = value;
}
};
});
App.controller("ParentCtrl", function($scope, MyParentService,SharedModel) {Child controller. Angularjs support inheritance of controllers.
$scope.parentMethod = function(){
SharedModel.updateValue({'par1' : 'myValue'});
console.info('do something');
}
});
App.controller("DefaultCtrl", function($scope, $controller, SharedModel, MyService) {Top service body.
$controller('ParentCtrl', {$scope: $scope});
$scope.setVal = function(text){
MyService.setText(text);
sharedModel.updateValue(text);
};
$scope.getVal = function(){
return SharedModel.getValue();
};
$scope.getServiceVal = function(){
return MyService.myBase();
};
$scope.getMyServiceVal = function(){
return MyService.myService();
};
});
function MyBaseService($http) {Medium service body.
this.text = "MyBaseServiceText";
this.loaded = false;
this.myBase = function(){
console.log("MyBaseService.myBase");
if(!this.loaded){
$http({
method: 'GET',
url: 'http://localhost/',
});
this.loaded = true;
}
return this.text;
}
};
Child service body used in controller.
function MyParentService($http) {
MyBaseService.call(this,$http);
this.getSomething = function(){
return 'something';
}
};
Registration of service body in Angularjs's context.
function MyService($http) {
MyBaseService.call(this,$http);
this.myService = function(){
console.log("called my service" + this.text);
$http({
method: 'GET',
url: 'http://localhost/',
});
}
};
App.service("MyBaseService", MyBaseService);It's quite easy..... isn't it ?
App.service("MyParentService", MyParentService);
App.service("MyService", MyService);
No comments:
Post a Comment