I am an angular beginner and I have been working on this problem for a few days now but I haven't quite solved it. I am trying to create a directive where when the user highlights some text, a ui-bootstrap tooltip is automatically created around the selection. I have the following code that almost does what I want.
app.directive('selectOnClick', function ($window, $compile) {
return {
link: function (scope, element) {
element.on('mouseup', function () {
if (window.getSelection) {
var sel = window.getSelection();
var template = '<a href="#" uib-tooltip="hello">'+sel.toString()+'</a>';
replaced = element.html().replace(new RegExp(sel.toString(), "g"), template);
element.html(replaced);
$compile(element.contents())(scope);
}
});
}
}
});
The problem with the above code is that it replaces EVERY instance of the selected text with the tooltip - I just want to put the tooltip around the actual text that was selected.
I have seen posts like this one that show how to replace selected text with span
elements in the following way
function surroundSelection() {
var span = document.createElement("span");
span.style.fontWeight = "bold";
span.style.color = "green";
if (window.getSelection) {
var sel = window.getSelection();
if (sel.rangeCount) {
var range = sel.getRangeAt(0).cloneRange();
range.surroundContents(span);
sel.removeAllRanges();
sel.addRange(range);
}
}
}
But I don't think this method is compatible with ui-bootstrap elements like tooltips. I am quite stuck on this so any advice would be greatly appreciated.