I'm new with angular and trying to do some directives nesting, but having some problems.
Here is my code :
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
};
});
my templates :
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>
my index.html :
[...]
<body>
<timeline></timeline>
</body>
And the unexpected result :
timeline ohoh
- event 12
- event 13
timeline element o/ \o
The expected result would be of course :
timeline ohoh
- event 12
timeline element o/ \o
- event 13
timeline element o/ \o
Why would the ng-repeat execute successfully, but the nested directive call only execute once? Is it not supposed to be able to use directives in loops?
Three remarks. I don't know if these are the cause (need to test it in a jsFiddle for that), but they are surely breaking something:
Why do you set transclude: true
? You don't use ng-transclude
in your template. You don't need transclude: true
.
the ng-model
on your timeline
should be element
instead of {{element}}
You are using scope: true
, which means a new scope will be created. You probably will need to define your scope
like (on both your directives).
Thus:
scope: {
element: '&' // provides a way to execute an expression in the context of the parent scope.
}