2017-04-10 49 views
2

嗨试图要求对同一元素。根据角度文档,这是可能的。角度指令要求在同一元素上

A^prefix would make the directive look for the controller on its own element or its parents; without any prefix, the directive would look on its own element only.

继解释。我有两个指令,myD和myC ...希望能够从myC的链接ctrl属性访问myD。

我已经包含一个指向我的codepen示例的链接。

var app = angular.module("app",[]); 


app.directive("myD", function() { 
    return { 
     restrict : "E", 
     template : "<b>myd</d>" 
    } 
}); 

app.directive("myC", function() { 
    return { 
     require : "myD", 
     restrict : "A", 
     link : function (scope, attr, ele, ctrl) { 
     alert(JSON.stringify(ctrl)); 
     } 
    } 

}); 

<div ng-app="app"> 
    <my-d my-c></my-d> 
</div> 

http://codepen.io/mantisimo/pen/KWOxeg

得到以下错误:

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

+1

把控制器:function(){}指令里面'myD'? – ABOS

+0

谢谢你......真的只是想到了它! :-) – Mantisimo

回答

2

当您使用require,你问的角度来注入所需的元素的控制器。在你的情况下,控制器是未定义的。

错误在myD您需要声明控制器。

app.directive("myD", function() { 
    return { 
     restrict : "E", 
     template : "<b>myd</d>", 
     controller: function(){} 
    } 
}); 
+1

只是两秒钟前计算出来......当你定义问题时,你会发现问题很有趣......感谢你的快速反应。 – Mantisimo

+0

希望能拯救别人一些痛苦:) – Mantisimo

+1

@Mantisimo下一次,使用塑料鸭;-) –