我使用angular 1.5開發我的應用程序,我使用.component(),我有三個組件和他的控制器非常相似。我怎樣才能從comp1擴展控制器使用它與comp2?擴展控制器組件 - angularjs
在單獨的js文件中的每個組件。
comp1.js comp2.js comp3.js
我使用angular 1.5開發我的應用程序,我使用.component(),我有三個組件和他的控制器非常相似。我怎樣才能從comp1擴展控制器使用它與comp2?擴展控制器組件 - angularjs
在單獨的js文件中的每個組件。
comp1.js comp2.js comp3.js
可以從彼此延伸組件控制器也是如此。 用下面的辦法:
父組件(從延長):
/**
* Module definition and 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;
};
});
兒童成分(一種增量):
/**
* Module definition and 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;
};
});
您可以在子控制器定義新的方法,覆蓋現有方法,調用父方法等。工作得很好。
我可能會建議你只是使用服務來共享和組成組件。然後,您可以跳過複雜擔心.extend()
,$controller
的等
angular
.module('app')
.factory('component.utils', function() {
return {
sharedProp: 'foo',
sharedMethod: function() { return 'bar' }
}
})
// components can all easily use functionality
// provided by one (or more) services, w/o
// needing a complicated inheritance model.
.component('foo', {
templateUrl: 'foo.html',
controller: [
'component.utils',
function(utils) {
this.$onInit = function() {
this.prop = utils.sharedProp;
utils.sharedMethod();
// now do other foo things...
}
}
]
})
.component('bar', {
templateUrl: 'foo.html',
controller: [
'component.utils',
function(utils) {
this.$onInit = function() {
this.prop = utils.sharedProp;
utils.sharedMethod();
// now do other bar things...
}
}
]
});
繼承有它的地方,但有利於組成了繼承通常是更好的解決方案。 article。
是[this](http://stackoverflow.com/a/20230720/6263032)你在找什麼? – domyos
不幸的是,這個答案談到了控制器,而不是.component() – Amine
這與組件無關。在Angular 1.5中,組件只是編寫指令的一種更簡單的方法。組件/指令使用控制器的方式與使用ng-controller註釋和使用html-tag相同。 – domyos