首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >为什么我不能从父指令中要求一个子指令?

为什么我不能从父指令中要求一个子指令?
EN

Stack Overflow用户
提问于 2014-01-08 20:33:23
回答 2查看 1.2K关注 0票数 3

普鲁克尔抛出此错误:

Error: [$compile:ctreq] Controller 'childDirective', required by directive 'parentDirective', can't be found!

我可以解决这个问题,但我很好奇这是否是精心设计的,为什么(单亲还是多个孩子)?在$ng.compile文档中,我没有看到任何提到这个限制的地方。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2014-01-09 00:26:00

之所以没有实现这一点是因为性能。遍历DOM比检查每个子分支的可能匹配要快得多。因此,建议的方法是让子元素将其状态通知其父元素。

注意,这是通过关联的控制器实例完成的,而不是通过指令完成的。

我用工作实例更新了你的键盘

代码语言:javascript
运行
复制
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);
    }
  };
});
票数 6
EN

Stack Overflow用户

发布于 2014-01-08 21:44:32

你不能要求一个子指令,据我所知,在角度上是不允许的。只能通过以下方式要求来自子节点的父指令:

代码语言:javascript
运行
复制
require: '^parentDirectiveName'

或者是兄弟姐妹指令

代码语言:javascript
运行
复制
require: 'siblingDirectiveName'

因此,是的,这是由设计,或至少缺乏功能。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/21005911

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档