In an attempt to streamline my code, I've created a directive that automatically adds certain attributes to all anchor tags in a given list. This way, I don't have to keep duplicating the same code over and over again.
While this approach has been successful, I'm encountering an issue when launching a modal with dynamically decorated links. Instead of rendering the image, I'm getting the raw image code. During testing, manually applying the directive to a few links at the top worked perfectly by decorating the bootstrap modal attributes.
Here is the directive responsible for decorating all the anchors in a list:
angular.module('wmApp.wmAddImageModal', [])
.directive('wmAddImageModal', function() {
return {
restrict: 'A',
link: function ($scope, element, $attrs) {
var anchors = element.find('a');
angular.forEach(anchors, function (anchor) {
var a = angular.element(anchor);
a.attr('data-wm-image-modal', '');
a.attr('data-toggle', 'modal');
a.attr('data-target', '#wm-modal');
});
}
};
});
This is the directive for handling the behavior when links are clicked. I also tried using data-ng-src
, but it did not solve the issue:
angular.module('wmApp.wmImageModal', [])
.directive('wmImageModal', function() {
return {
restrict: 'A',
link: function($scope, element, $attrs) {
element.on('click', function($event) {
$event.preventDefault();
var imgUrl = window.location.origin + '/' + $attrs.href;
var content = '<div class="modal-header"><h3 class="modal-title">' + $attrs.title + '</h3></div>' +
'<div class="model-body"><img src="' + imgUrl + '" width="100%"></div>';
$('#wm-modal .modal-content').html(content);
});
}
};
});
For clarity, here is the bootstrap modal structure I am using. Note that the whole modal is a sibling to the list, not a child element of the directive's element:
<div class="modal fade" id="wm-modal" role="dialog">
<div class="modal-dialog modal-lg">
<div class="modal-content"></div>
</div>
</div>
The original list of anchors in its raw form:
<ul data-wm-add-image-modal>
<li>
<h4>
<a href="path/to/image.png" title="An awesome description">
2016: Screenshot</a>
</h4>
<p>
An awesome description
</p>
</li>
...
</ul>
After applying the wm-add-image-modal
directive to each anchor in the list:
<ul data-wm-add-image-modal>
<li>
<h4>
<a href="path/to/image.png" title="An awesome description" data-wm-image-modal data-toggle="modal" data-target="#wm-modal">
2016: Screenshot</a>
</h4>
...
</li>
...
</ul>
Despite setting up the directives properly, the images are not loading as expected in the modal. Additional debugging reveals some interesting findings. Any suggestions on how to address this issue would be greatly appreciated!