问题描述
能子指令要求没有确切知道父母该指令,家长,只是它实现一个接口?
例如:
< parentImplX>
<儿童>< /儿童>
< / parentImplX>
在上面的例子我想注入的孩子将控制器 ParentImplXCtrl
。但是,如果我做的:
< parentImplY>
<儿童>< /儿童>
< / parentImplY>
我想将控制器 ParentImplYCtrl
。
directives.directive(parentImplX功能(){
返回{
范围: {},
限制:E,
控制器:ParentImplXCtrl
}
});directives.directive(parentImplY功能(){
返回{
范围: {},
限制:E,
控制器:ParentImplYCtrl
}
});directives.directive(子,函数(){
返回{
范围: {},
限制:E,
要求:^^ parentInterface
链接:功能($范围,$元素,属性,父/ *类型ParentInterface * /){
parent.method();
}
}
});
我发现角'要求'不支持这一点。然而,AngularJS存储控制器以及在 $范围
$元素
■在的$ element.data()
结构。所以这是写自己的界面需要'非常简单。您需要遍历 $ element.parent()数据()
,并确保有一个标识符寻找。在我的情况 isFocusNode
。注意:`FocusNode可以有多种实现。这是整点。
函数findFocusNodeParent(_Element){
VAR数据= _element.data();
对于(数据VAR键){
VAR angularObject =数据[关键]
如果(angularObject.isFocusNode&放大器;&放大器; angularObject.isFocusNode()){
返回angularObject;
}
}
变种_parentElement = _element.parent();
如果(_parentElement.length大于0){
返回findFocusNodeParent(_parentElement);
}其他{
//没有父FocusNode找到。必须是根
返回null;
}
}
变种parentFocusNodeController = findFocusNodeParent($元件);
Can a child directive require a parent without knowing exactly which directive that parent is, just that it "implements an interface"?
For example:
<parentImplX>
<child></child>
</parentImplX>
In the above example I want the controller injected into child to be ParentImplXCtrl
. But If I do:
<parentImplY>
<child></child>
</parentImplY>
I want the controller to be 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();
}
}
});
I've found that angular 'require' does not support this. However, AngularJS stores the controllers as well as the $scopes
of $element
s 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通用父指令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!