I am facing an issue with a directive that dynamically adds divs to the template. Every time I add a new one, the previously created ones are replaced by the new content. I have tried isolating the directive's scope using scope: {}
and scope: true
, but it does not seem to work.
This is the directive code:
angular.module('bucket.directives', [])
.directive('bucketList', ['$compile', function($compile) {
var viaUrlTemplate = '<span class="bucketItem viaUrl">{{ displayName }} <i class="icon-delete">x</i></span>';
return {
restrict: 'A',
link: function(scope, element, attrs) {
scope.$on('urlBucketAdded', function(event, bucketInfo) {
scope.displayName = bucketInfo.bucketName;
scope.$apply(function() {
var content = $compile(viaUrlTemplate)(scope);
element.append(content);
});
});
}
}
}]);
The structure of the HTML looks like this:
<div bucket-list class="bucketList">
// new elements in 'viaUrlTemplate' get inserted here
</div>
When trying to add new elements with displayName -> Content 1, Content 2, and Content 3, the result is:
<div bucket-list class="bucketList">
<span class="bucketItem viaUrl"> Content 3 <i class="icon-delete">x</i></span>
<span class="bucketItem viaUrl"> Content 3 <i class="icon-delete">x</i></span>
<span class="bucketItem viaUrl"> Content 3 <i class="icon-delete">x</i></span>
</div>
Any help or suggestions would be greatly appreciated. Thank you!