2014-05-21 23 views
1

我無法在指令中加載控制器的父代。我有兩個指令: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); 
     } 
    }; 
}) 
+0

是否完全有必要以這種方式共享控制器更新的jsfiddle,你不能依靠繼承範圍這樣的 - http://jsfiddle.net/gspVe/ 5/ – Neil

+0

他們爲什麼需要終端?只有當你在同一個元素上有多個指令時才重要。看起來不像你使用它們的方式。 – aet

+0

感謝您的想法@Neil,但我不能這樣做,因爲我需要獲取該指令的控制器。這個控制器有一些功能,我會從另一個範圍調用。 –

回答

0

只是想了解你想要做什麼。如果您想要替換HTML元素,爲什麼不使用指令提供的某些功能?

例如,它看起來像你試圖用<ul><li>替換指令元素。而不是將此定義爲你指出的,那麼您爲什麼不能做到以下幾點:

angular.module("test", []) 

.directive("hMenu", function() { 
    return { 
     restrict: "E", 
     transclude : true, 
     replace : true, 
     template : "<ul ng-transclude></ul>" 
    }; 
}) 

.directive("hMenuItem", function() { 
    return { 
     restrict: "E", 
     replace : true, 
     transclude : true, 
     template : '<li ng-transclude></li>' 
    }; 
}) 

然後,您可以使用的角度權力指示菜單項聲明,例如:

<div ng-app="test"> 
    <h-menu ng-init="menuitems=['Menu #1', 'Menu #2', 'Menu #3']"> 
     <h-menu-item ng-repeat="m in menuitems"> 
      {{m}} 
     </h-menu-item> 
    </h-menu> 
</div> 

這將顯示:

  • 菜單#1
  • 2號菜單
  • 3號菜單

我在http://jsfiddle.net/gspVe/9/

+0

嗨@rchawdry,謝謝你你的建議。我知道我可以做到,但在我的情況下,我不能因爲h-menu具有一些難以解釋的特性。 但是,嘗試終端沒有成功後,我做了它像你的想法,但我需要放棄一些特殊性。 乾杯! –

相關問題