angularjs - 为什么我不能要求父指令提供子指令?

标签 angularjs angularjs-directive

这个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/

相关文章:

javascript - Angularjs ng 类样式

javascript - 带有 Angularjs 的 json 表

angularjs - 一次性绑定(bind)到自定义属性指令

javascript - 将一个属性从一个指令绑定(bind)到另一个指令

java - org.apache.catalina.connector.RequestFacade 无法转换为 org.springframework.web.multipart.MultipartHttpServletRequest

javascript - Angular 中的 $http 请求后,链接函数中未定义数据

javascript - AngularJS ui-router 登录认证

angularjs - splice() 元素时完成 ng-repeat 的 Angular 指令

javascript - 独立滚动父子div

Angular js : accessing service methods from directive's link function