Skip to content

Instantly share code, notes, and snippets.

@nikita-graf
Last active August 29, 2015 14:26
Show Gist options
  • Save nikita-graf/3828bfdf7ce9ff78fcb3 to your computer and use it in GitHub Desktop.
Save nikita-graf/3828bfdf7ce9ff78fcb3 to your computer and use it in GitHub Desktop.
Simple AngularJS controller inheritance
var originalModule = angular.module;
angular.module = function (name, modules) {
var mod = originalModule.apply(angular, arguments);
var injector = angular.injector(modules ? ['ng'].concat(modules) : ['ng']);
mod.inheritController = function (name, Parent, Child) {
function Inherit($controller, $scope) {
var method;
var ctrl = $controller(Parent, {
$scope: $scope
});
for (method in ctrl) {
this[method] = ctrl[method];
}
;
Child.apply(this, Array.prototype.slice.call(arguments, 2));
}
Inherit.$inject = ['$controller', '$scope'].concat(injector.annotate(Child));
this.controller(name, Inherit);
return this;
};
return mod;
};
// Usage
var myApp = angular.module('myApp',[])
.controller('BaseCtrl', function() {
this.a = function() {};
})
.inheritController('ExtendedCtrl', 'BaseCtrl', function() {
this.a();
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment