为什么我不能从父指令中要求子指令?
-
20-12-2019 - |
题
这个 plunkr 抛出此错误:
Error: [$compile:ctreq] Controller 'childDirective', required by directive 'parentDirective', can't be found!
我可以解决这个问题,但如果这是符合设计,我很好奇,以及为什么(单亲vs多个孩子的东西)?我没有看到 $ ng.compile docs 中提到任何提及此限制。
解决方案
这不是实现的原因是性能。遍历DOM的速度快,而不是检查每个子分支以进行可能的匹配。出于这个原因,推荐的方式是让子元素通知他们的父母的状态。
请注意,这是通过关联的控制器实例完成的,而不是通过指令完成。
我用一个工作示例
angular.module('foo', [])
.directive('parentDirective', function() {
return {
controller: function($scope) {
$scope.childs = {};
this.registerChild = function(child) {
$scope.childs[child.name] = child;
};
},
link: function(scope, element, attrs) {}
};
})
.directive('childDirective', function() {
return {
controller: function($scope) {},
require: ['^parentDirective', 'childDirective'],
link: function($scope, $element, $attrs, $ctrls) {
var parent = $ctrls[0];
var child = $ctrls[1];
child.name = $attrs.childDirective;
parent.registerChild(child);
}
};
});
. 其他提示
你不能要求子指令,据我所知,在角度上都没有允许这个。您只能从孩子中需要父指令
require: '^parentDirectiveName'
.
或兄弟指令,by
require: 'siblingDirectiveName'
.
所以是的,这是通过设计,或者至少缺乏特征。
不隶属于 StackOverflow