javascript - extend controller component - angularjs -


i use angular 1.5 develop application use .component() , had thre component , controllers quite similar. how can extend controller comp1 use comp2?

each component in seperate js file.

comp1.js comp2.js comp3.js

you can extend component controllers each other well. use following approach:

parent component (to extend from):

/**  * module definition , dependencies  */ angular.module('app.parent', [])  /**  * component  */ .component('parent', {   templateurl: 'parent.html',   controller: 'parentctrl', })  /**  * controller  */ .controller('parentctrl', function($parentdep) {    //get controller   const $ctrl = this;    /**    * on init    */   this.$oninit = function() {      //do stuff     this.something = true;   }; }); 

child component (the 1 extending):

/**  * module definition , dependencies  */ angular.module('app.child', [])  /**  * component  */ .component('child', {   templateurl: 'child.html',   controller: 'childctrl', })  /**  * controller  */ .controller('childctrl', function($controller, $parentdep) {    //get controllers   const $ctrl = this;   const $base = $controller('parentctrl', {$parentdep});    //extend   angular.extend($ctrl, $base);    /**    * on init    */   this.$oninit = function() {      //call parent init     $base.$oninit.call(this);      //do other stuff     this.somethingelse = true;   }; }); 

you can define new method in child controller, overwrite existing methods, call parent methods, etc. works well.


Comments

Popular posts from this blog

sql - invalid in the select list because it is not contained in either an aggregate function -

Angularjs unit testing - ng-disabled not working when adding text to textarea -

How to start daemon on android by adb -