我可以在 AngularJS 中要求通用父指令吗 [英] Can I require generic parent directive in AngularJS

查看:22
本文介绍了我可以在 AngularJS 中要求通用父指令吗的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

子指令是否可以在不确切知道父指令是哪个指令的情况下要求父指令,只是它实现了一个接口"?

Can a child directive require a parent without knowing exactly which directive that parent is, just that it "implements an interface"?

例如:

<parentImplX>
  <child></child>
</parentImplX>

在上面的例子中,我希望注入到 child 中的控制器是 ParentImplXCtrl.但如果我这样做:

In the above example I want the controller injected into child to be ParentImplXCtrl. But If I do:

<parentImplY>
  <child></child>
</parentImplY>

我希望控制器是 ParentImplYCtrl.

directives.directive("parentImplX", function () {
  return {
    scope: {},
    restrict: "E", 
    controller: ParentImplXCtrl
  }
});

directives.directive("parentImplY", function () {
  return {
    scope: {},
    restrict: "E", 
    controller: ParentImplYCtrl
  }
});

directives.directive("child", function () {
  return {
    scope: {},
    restrict: "E",
    require: "?^^parentInterface",
    link: function ($scope, $element, attributes, parent /* type ParentInterface */) {
      parent.method();
    }
  }
});

推荐答案

我发现 angular 'require' 不支持这个.但是,AngularJS 将控制器以及 $element$scopes 存储在 $element.data() 构造中.因此,编写自己的接口要求"非常简单.您需要遍历 $element.parent().data() 并确保有一个要查找的标识符.就我而言,isFocusNode.注意:`FocusNode 可以有很多实现.这是重点.

I've found that angular 'require' does not support this. However, AngularJS stores the controllers as well as the $scopes of $elements in the $element.data() construct. So it was very simple to write your own 'interface require'. You need to traverse $element.parent().data() and make sure there is an identifier to look for. In my case isFocusNode. Note: `FocusNode can have many implementations. It is the whole point.

  function findFocusNodeParent(_element) {
    var data = _element.data();
    for (var key in data) {
      var angularObject = data[key];
      if (angularObject.isFocusNode && angularObject.isFocusNode()) {
        return angularObject;
      }
    }
    var _parentElement = _element.parent();
    if (_parentElement.length > 0) {
      return findFocusNodeParent(_parentElement);
    } else {
      // No parent FocusNode found. Must be root
      return null;
    }
  }
  var parentFocusNodeController = findFocusNodeParent($element);

这篇关于我可以在 AngularJS 中要求通用父指令吗的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆