这plunkr抛出这个错误:为什么我不需要父指令的子指令?
Error: [$compile:ctreq] Controller 'childDirective', required by directive 'parentDirective', can't be found!
我可以解决这个问题,但我很好奇,如果这是特意设计的,为什么(单亲VS多个孩子的事)?在$ng.compile docs中我没有看到任何此限制。
这plunkr抛出这个错误:为什么我不需要父指令的子指令?
Error: [$compile:ctreq] Controller 'childDirective', required by directive 'parentDirective', can't be found!
我可以解决这个问题,但我很好奇,如果这是特意设计的,为什么(单亲VS多个孩子的事)?在$ng.compile docs中我没有看到任何此限制。
未实现的原因是性能。遍历DOM比检查每个子分支可能的匹配要快得多。出于这个原因,推荐的方法是让子元素通知他们的父母其状态。
请注意,这是通过关联的控制器实例完成的,而不是通过指令完成的。
我已经与working example
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);
}
};
});
更新您的普拉克
据我所知,Angular允许这样做,你不能要求一个子指令。你可以只需要从孩子父母的指令,通过
require: '^parentDirectiveName'
或兄弟姐妹的指令,通过
require: 'siblingDirectiveName'
所以,是的,这是由设计,或至少缺乏功能。