Last active
August 29, 2015 14:26
-
-
Save nikita-graf/3828bfdf7ce9ff78fcb3 to your computer and use it in GitHub Desktop.
Simple AngularJS controller inheritance
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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