我無法在指令中加載控制器的父代。我有兩個指令:h-menu和h-menu-item。 h-menu使用控制器,而h-menu-item需要該控制器。終端爲真時需要指令中的控制器
但是h-menu指令有terminal = true,並且用這個我不能加載控制器。當我將終端設置爲false時,我可以加載控制器。
的jsfiddle:http://jsfiddle.net/gspVe/4/
HTML:
<div ng-app="test">
<h-menu>
<h-menu-item>
</h-menu-item>
</h-menu>
</div>
下面是代碼JS:
angular.module("test", [])
.controller("hMenu", function() {
this.msg = "controller was loaded";
return this;
})
.directive("hMenu", function($compile) {
return {
restrict: "E",
// comment this and controller will be loaded
terminal: true,
controller: "hMenu",
require: "hMenu",
link: function (scope, element, attrs) {
var ul = $("<ul/>");
ul.append(element.children());
$compile(ul)(scope);
element.replaceWith(ul);
}
};
})
.directive("hMenuItem", function($compile) {
return {
restrict: "E",
terminal: true,
require: "?^hMenu",
link: function (scope, element, attrs, controller) {
var li = $("<li/>");
if (controller)
li.html(controller.msg);
else
li.html("contoller not loaded!");
$compile(li)(scope);
element.replaceWith(li);
}
};
})
是否完全有必要以這種方式共享控制器更新的jsfiddle,你不能依靠繼承範圍這樣的 - http://jsfiddle.net/gspVe/ 5/ – Neil
他們爲什麼需要終端?只有當你在同一個元素上有多個指令時才重要。看起來不像你使用它們的方式。 – aet
感謝您的想法@Neil,但我不能這樣做,因爲我需要獲取該指令的控制器。這個控制器有一些功能,我會從另一個範圍調用。 –