Skip to content

Instantly share code, notes, and snippets.

@boneskull
Created July 16, 2013 19:13
Show Gist options
  • Save boneskull/6011707 to your computer and use it in GitHub Desktop.
Save boneskull/6011707 to your computer and use it in GitHub Desktop.
Example of service inheritance
var myApp = angular.module('myApp', []);
var baseService = function () {
this._state = {};
};
baseService.prototype.getState = function () {
return this._state;
};
baseService.prototype.setState = function (state) {
this._state = state;
};
var chartService = function () {
this._seriesParam = {};
};
chartService.prototype = Object.create(baseService.prototype);
chartService.prototype.getSeriesParam = function () {
return this._seriesParam;
};
chartService.prototype.setSeriesParam = function (seriesParam) {
this._seriesParam = seriesParam;
};
myApp.service('baseService', baseService);
myApp.service('chartService', chartService);
function MyCtrl($scope, chartService) {
var state = {
foo: 'bar'
},
seriesParam = {
baz: 'spam'
};
chartService.setState(state);
$scope.state = chartService.getState();
chartService.setSeriesParam(seriesParam);
$scope.seriesParam = chartService.getSeriesParam();
}
@nschurmann
Copy link

It's not necessary to add methods to the prototype thus the services are singletons.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment