Is there a way to pass the URL of an anchor tag in the directive to the controller function "itemClicked"? The code below successfully logs the "post" object when clicked.
HTML:
<div ng-repeat="post in posts" >
<div find-urls link-clicked="itemClicked(post)" ng-bind="post.content"><div>
</div>
Controller:
$scope.itemClicked = function(post) {
console.log(post);
};
Directive:
function findUrls($compile) {
return {
restrict: 'AC',
scope: {
linkClickedCallback: '&linkClicked'
},
link: function (scope, elem, attrs) {
if (attrs.ngBind) {
scope.$watch(attrs.ngBind, _.debounce(wrapUrls));
}
if (attrs.ngBindHtml) {
scope.$watch(attrs.ngBindHtml, _.debounce(wrapUrls));
}
function wrapUrls(text) {
var linkPatterns = new Array({
pattern: /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig,
template: ' <a class="absolute_link" href="$1" target="_blank">$1</a>'
},
{
pattern: /(^|[^\/])(www\.[\S]+(\b|$))/ig,
template: ' <a class="absolute_link" href="http://$2" ng-click="linkClickedCallback();" target="_blank">$2</a>'
},
{
pattern: /([a-z0-9._-]+@[a-z0-9._-]+\.[a-zA-Z0-9._-]+)/ig,
template: ' <a class="absolute_link" href="mailto:$1" ng-click="linkClickedCallback();" target="_blank">$1</a>'
},
{
pattern: /(^|[^a-z0-9@\\\/._-])([a-z0-9]{0,256}\.(com|net|org|edu)([a-z0-9\/?=\-_#]{0,256})?(\b|$))/ig,
template: ' <a class="absolute_link" href="http://$2" ng-click="linkClickedCallback();" target="_blank">$2</a>'
});
var html = elem.html();
var newHtml = html;
linkPatterns.forEach((item) => {
newHtml = newHtml.replace(item.pattern, item.template);
});
if (html !== newHtml) {
elem.html(newHtml);
$compile(elem.contents())(scope);
}
}
}
};
}