Why is my external template not rendering items using ng-repeat
?
--- AngularJS 1.1.5
I stumbled on this bug but I'm not sure if it's the same issue? If it is are there any work arounds?
Here's a Plunker using a static list but the solution needs to support two way binding because the data is dynamic. ( That's how it's supposed to work anyway... )
controller
.controller('main', ['$scope',function($scope) {
$scope.items = ['a','b','c'];
}])
directive
.directive('items', function() {
return {
restrict: 'E',
replace: true,
controller: 'main',
templateUrl: 'items.html',
link: function(scope, controller) {
}
};
})
items.html
<div ng-repeat="item in items">
{{item}}
</div>
Why is my external template not rendering items using ng-repeat
?
--- AngularJS 1.1.5
I stumbled on this bug but I'm not sure if it's the same issue? If it is are there any work arounds?
Here's a Plunker using a static list but the solution needs to support two way binding because the data is dynamic. ( That's how it's supposed to work anyway... )
controller
.controller('main', ['$scope',function($scope) {
$scope.items = ['a','b','c'];
}])
directive
.directive('items', function() {
return {
restrict: 'E',
replace: true,
controller: 'main',
templateUrl: 'items.html',
link: function(scope, controller) {
}
};
})
items.html
<div ng-repeat="item in items">
{{item}}
</div>
Share
Improve this question
edited Aug 3, 2013 at 16:37
Dan Kanze
asked Aug 2, 2013 at 15:02
Dan KanzeDan Kanze
18.6k28 gold badges84 silver badges136 bronze badges
3 Answers
Reset to default 3This is because your directive uses a template that does not have on root element, try:
<div>
<h1>What?</h1>
<div ng-repeat="item in items">
{{item}}
</div>
</div>
for the template.
EDIT: To understand this, we can have a look at the source of angular itself. The pile-Methods responsible for this can be looked at here. The culprit is the mergeTemplateAttributes and the need for one root bees apparent when looking at the intent here: When replacing DOM nodes, angular needs to pass on the attributes. When there is more than one node in the template fetched it will throw an error, as it cannot decide on the node which the original attributes will be applied to (see here for the error thrown).
The quote the developers here:
When the element is replaced with HTML template then the new on the template need to be merged with the existing attributes in the DOM. The desired effect is to have both of the attributes present.
Update your items.html as below:
<div>
<h1>What?</h1>
<div ng-repeat="item in items">
{{item}}
</div>
</div>
You need to wrap the template with one root like this:
<div>
<h1>What?</h1>
<div ng-repeat="item in items">
{{item}}
</div>
</div>