扩展控制器组件angularjs
extend controller component - angularjs
我使用angular 1.5来开发我的应用程序,我使用.component()
。我有三个组件和它们的控制器,它们都很相似。如何将控制器从comp1
扩展到comp2
?
每个组件在单独的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...
}
}
]
});
继承有它的位置,但倾向于组合而不是继承通常是更好的解决方案。篇文章。
相关文章:
- AngularJS'不可知论者;和'组件'指令
- AngularJS适合构建组件
- AngularJS组件和cms驱动应用程序的最佳实践
- AngularJS 组件用户
- AngularJS - 接收动态内容的组件
- React 组件中的 AngularJS 过滤器
- AngularJS:在组件之间进行通信的最佳实践是什么?
- AngularJS服务初始化并获取第三方组件
- AngularJS通过嵌套组件向上传播更改
- AngularJS 1.5:组件获胜't加载http数据
- angularjs组件的执行顺序是什么
- 如何在一个视图中多次正确使用同一个AngularJS 1.5组件
- 使用Gulp时AngularJS组件配置错误
- AngularJS组件定义为函数
- D3.js 4与AngularJS 1.5(组件或指令?).
- 如何在没有双向绑定的情况下将ngModel传递给AngularJS组件
- AngularJS组件可以修改它们的包装元素吗?
- AngularJS 1.5 组件中的第三方异步回调
- 如何在同一页面中多次使用 AngularJS 2 组件
- AngularJS 1.5组件迁移指令,从组件中调用Page函数