2013-01-09 65 views
1

我是新的角度和嘗試做一些指令嵌套,但有一些問題。在angularjs中循環嵌套指令

這裏是我的代碼:

module.controller("TimelineController", ["$scope", "$compile", function ($scope, $compile) { 

    $scope.text = "ohoh"; 
    $scope.elements = ["12", "13"]; 

    console.log("Timeline Controller", arguments); 

}]); 

module.directive('timeline', function() { 
    return { 
     restrict: 'E', 
     transclude: true, 
     scope: true, 
     controller : "TimelineController", 
     link: function(scope, element, attrs, controller) { 
      console.log("linking timeline", arguments); 
     }, 
     templateUrl:'templates/directives/timeline.html', 
     replace: true 
    }; 
}); 

module.directive('timelineEvent', function() { 
    return { 
     restrict: 'E', 
     transclude: true, 
     scope: true, 
     // controller : "TimelineController", 
     link: function(scope, element, attrs/*, controller*/) { 
      console.log("linking element", arguments); 
     }, 
     templateUrl:'templates/directives/timeline_element.html', 
     replace: false 
    }; 
}); 

我的模板:

timeline.html:

<div class="timeline"> 
    <p> 
     timeline {{text}} 
    </p> 

    <div ng-repeat="element in elements"> 
     - event {{element }} 
     <timeline-event ng-model="{{element}}"/> 
    </div> 

</div> 

timeline_element.html:

<div class="element"> 
    timeline element o/ \o 
</div> 

我的index.html:

[...] 
<body> 

    <timeline></timeline> 

</body> 

而且意想不到的結果:

timeline ohoh 

- event 12 
- event 13 
timeline element o/ \o 

預期的結果將是當然的:

timeline ohoh 

- event 12 
timeline element o/ \o 
- event 13 
timeline element o/ \o 

爲什麼會NG-重複成功執行,但嵌套指令調用只執行一旦?它不應該能夠在循環中使用指令嗎?

回答

3

三條評論。我不知道這些都是原因(需要測試它在的jsfiddle爲該),但他們肯定打破了一句:

  • 你爲什麼要設置transclude: true?您不要在模板中使用ng-transclude。你不需要transclude: true

  • ng-modeltimeline應該element而不是{{element}}

  • 您正在使用scope: true,這意味着一個新的範圍將被創建。你可能需要定義你的scope(在你的兩個指令上)。

因此:

scope: { 
    element: '&' // provides a way to execute an expression in the context of the parent scope. 
} 
+0

工作[小提琴](http://jsfiddle.net/mrajcok/fKbtt /)。它遵循@asgoth的建議,除了你不需要創建一個新的範圍,所以'scope:'行被註釋掉了。 –

+0

這個例子有一個錯字「ng-controlle」,但它沒有它,所以很奇怪! – iamwhitebox

+0

這真的很奇怪。如果綁定控制器,它不起作用。 WTF!? – schlingel

0

@馬克Rajcok請改變下列行來

<div ng-controlle="TimelineControllerCtrl"> 

<div ng-controller="TimelineController">