【发布时间】:2016-05-19 12:49:36
【问题描述】:
根据the docs(具体而言,将指令与组件进行比较的表格),角度组件允许需要其他指令(或者它只是组件?)。但是,组件没有链接功能,它可以访问所需的控制器。 The source,与文档相反,似乎暗示在创建组件时不能使用“require”。哪个是真的?
【问题讨论】:
标签: javascript angularjs angular-directive
根据the docs(具体而言,将指令与组件进行比较的表格),角度组件允许需要其他指令(或者它只是组件?)。但是,组件没有链接功能,它可以访问所需的控制器。 The source,与文档相反,似乎暗示在创建组件时不能使用“require”。哪个是真的?
【问题讨论】:
标签: javascript angularjs angular-directive
引用的来源已过时。从 1.5.0 开始,其他组件中的组件控制器 can be required(同样适用于指令)。
1.5 中指南 shows the way how the components and directives should interact 的示例,没有 link 的帮助。
当require object and bindToController 一起使用时,所需的控制器实例将作为属性分配给当前控制器。
因为这发生在指令链接期间,所需的控制器在控制器构造函数中不可用,这就是$onInit magic method 存在的原因。如果存在,it is executed right after adding required controllers 到 this。
两者
app.directive('someDirective', function () {
return {
scope: {},
bindToController: {},
controllerAs: 'someDirective',
require: {
anotherDirective: '^anotherDirective'
},
controller: function ($scope) {
console.log("You don't see me", this.anotherDirective);
this.$onInit = function () {
console.log("Now you do", this.anotherDirective);
};
}
}
});
和
app.component('someComponent', {
controllerAs: 'someComponent',
require: {
anotherDirective: '^anotherDirective'
},
controller: function ($scope) {
console.log("You don't see me", this.anotherDirective);
this.$onInit = function () {
console.log("Now you do", this.anotherDirective);
};
}
});
声明样式在底层是相当的,可以在 1.5 中互换使用,component 是一种简洁的样式。
【讨论】: