这个plunkr抛出此错误:
错误:[$compile:ctreq] 找不到指令“parentDirective”所需的 Controller “childDirective”!
我可以解决这个问题,但我很好奇这是否是设计使然,为什么(单亲与多个 child 的事情)?我在 $ng.compile docs 中没有看到任何提及此限制的信息。 .
最佳答案
未实现此功能的原因是性能。遍历 DOM 比检查每个子分支是否有可能的匹配要快得多。因此,推荐的方法是让子元素通知其父元素其状态。
请注意,这是通过关联的 Controller 实例完成的,而不是通过指令。
我已经用 working example 更新了你的 plunk。
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);
}
};
});
关于angularjs - 为什么我不能要求父指令提供子指令?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21005911/