user1893354 user1893354 - 5 months ago 48
AngularJS Question

Create Popover from Text Selection

I am quite new to javascript and angularjs and I've hit a wall with this problem. Basically I'm trying to write a function that gets the selected text and creates a bootstrap popover around it. This is what I have so far

$scope.highlight = function () {

var a = document.createElement("a");
a.setAttribute('href', "#");
a.setAttribute('data-toggle','popover');
a.setAttribute('data-content','Some content inside the popover');
a.setAttribute('title','popover title');

if (window.getSelection) {
var sel = window.getSelection()
var range = sel.getRangeAt(0).cloneRange();
range.surroundContents(a);
sel.removeAllRanges();
sel.addRange(range);
}

};

$(document).ready(function(){
$('[data-toggle="popover"]').popover();
});


The above code does surround the selected text with the
<a href="#" data-toggle="popover" data-content="Some content inside the popover" title="popover title">
tag for the popover, however when you click on it no popover appears. Can someone tell me what I'm missing? Is this even the correct method to implement this?

Answer

Try something like that:

Controller:

 mymodule.controller('MainCtrl', [ '$scope', '$timeout',function ($scope,$timeout) {

    $scope.highlight = function () {

        var a = document.createElement("a");
        a.setAttribute('tabindex', "0");
        a.setAttribute('data-toggle','popover');
        a.setAttribute('data-content','Some content inside the popover');
        a.setAttribute('title','popover title');

        if (window.getSelection) {
                var sel = window.getSelection()
                var range = sel.getRangeAt(0).cloneRange();
                range.surroundContents(a);
                sel.removeAllRanges();
                sel.addRange(range);
        }
        $timeout(function(){
          $('[data-toggle="popover"]').popover();
        }, 50);
    };

  }]);

there are some small details that you have to pay attention to the popovers can be created correctly:

you need to add this atribute for popover (http://getbootstrap.com/javascript/#popovers):

a.setAttribute('tabindex', "0");

You have to call the popover function after adds the new structure for popovers and make the changes over the DOM the to initialize all popovers

$('[data-toggle="popover"]').popover();

Template:

<p>
  Lorem ipsum dolor sit amet, consectetur adipisicing elit. Dolor quos vel quam harum sapiente ea corporis magnam quo, voluptas tempore iure, aspernatur, quia accusamus soluta nostrum. Esse sapiente dignissimos excepturi.
</p>

<button class="btn btn-success" ng-click="highlight()">
  Create popover
</button>