Javascript 扩展控制器组件-angularjs
我使用angular 1.5开发我的应用程序,我正在使用Javascript 扩展控制器组件-angularjs,javascript,angularjs,components,Javascript,Angularjs,Components,我使用angular 1.5开发我的应用程序,我正在使用.component()。我有三个组件和它们的控制器,它们都非常相似。如何将控制器从comp1扩展到与comp2一起使用 单独js文件中的每个组件: comp1.jscomp2.jscomp3.js您还可以相互扩展组件控制器。 使用以下方法: 父组件(要从中扩展): 子组件(扩展的组件): 您可以在子控制器中定义新方法、覆盖现有方法、调用父方法等。这些方法非常有效。我建议您只需使用服务来共享和组合组件。然后,您可以跳过担心.extend()
.component()
。我有三个组件和它们的控制器,它们都非常相似。如何将控制器从comp1
扩展到与comp2
一起使用
单独js文件中的每个组件:
comp1.js
comp2.js
comp3.js
您还可以相互扩展组件控制器。
使用以下方法:
父组件(要从中扩展):
子组件(扩展的组件):
您可以在子控制器中定义新方法、覆盖现有方法、调用父方法等。这些方法非常有效。我建议您只需使用服务来共享和组合组件。然后,您可以跳过担心
.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...
}
}
]
});
继承有它的地位,但比起继承,更倾向于组合通常是更好的解决方案 这就是你要找的吗?不幸的是,这个答案是关于控制器而不是。component()这与组件无关。在Angular 1.5中,组件只是编写指令的简单方法。组件/指令使用控制器的方式与使用ng-controller进行注释和html标记的方式相同。您决定了什么?一个建议,虽然它需要一个主要的头绪,如果你仍然在盎格鲁JS在2020:考虑,这有助于抽象的扩展过程为你。
/**
* 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;
};
});
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...
}
}
]
});