angularjs - Javascript inheritance dependency on constructor parameter -


i implement prototypal inheritance in angular base type defined angular value. problem setting child type prototype. suppose simplified example:

file 1

angular.module("test")        .value("basecontroller", basecontroller);  basecontroller.$inject = [...];  function basecontroller(...) {     ... }  basecontroller.prototype.func = function () {     ... }; 

file 2

angular.module("test")        .controller("childcontroller", childcontroller);  childcontroller.$inject = ["basecontroller", ...];  function childcontroller(basecontroller, ...) {     basecontroller.call(this, ...);      // save reference later     childcontroller.base = basecontroller;     ... }  // error - why childcontroller.prototype = object.create(basecontroller.prototype);  // error - instance properties aren't available on level childcontroller.prototype = object.create(childcontroller.base.prototype); 

inheritance

the problem prototype being generated before constructor being instantiated. until constructor being instantiated have no possible reference of angular-injected basecontroller.

the way can see solve have basecontroller publically defined can access before angular injects constructor. don't can't have code private inside function closures , use angular's features as possible without having mixture of usual javascript against angular code.

main question

is there way make prototypal inheritance work having base types defined values (or other) in angular?

this solution approach. can use module's run block assign prototype. in file 2 add following:

angular.module("test").run(function(basecontroller) {   childcontroller.prototype = object.create(basecontroller.prototype); }); 

basecontroller gets injected , available creating prototype. since code runs before controller gets instantiated prototypal inheritance.

also keep in mind childcontroller.$inject has contain of basecontroller.$inject.

an alternative attach basecontroller module itself:

angular.module("test").basecontroller = basecontroller; ... childcontroller.prototype = object.create(angular.module("test").basecontroller.prototype); 

the code still private , constructor function still accessible through module.

you can alternatives inheritance. depending on situation hierarchical controllers might viable solution.

<div ng-controller="basecontroller"><%-- handle generic stuff --%>   ...   <div ng-controller="childcontroller"><%-- handle specific stuff --%> 

Comments

Popular posts from this blog

c++ - No viable overloaded operator for references a map -

java - Custom OutputStreamAppender not run: LOGBACK: No context given for <MYAPPENDER> -

java - Cannot secure connection using TLS -