0

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.

Community
  • 1
  • 1
user1893354
  • 5,778
  • 12
  • 46
  • 83

1 Answers1

1

When you get the matching text from the selection and going forward from there, the original context is already lost - you got no way to know which foo you have selected from if you have multiple in your paragraph.

In order to achieve what you need, you'll need to work on the selection itself, so you can pinpoint it for removal and addition of new content.

You can refer to this answer on how to do that: https://stackoverflow.com/a/6252893/5039495

Community
  • 1
  • 1
Icycool
  • 7,099
  • 1
  • 25
  • 33