I am looking for a custom directive that can capture and clear the current selection, then pass the selected text to a callback function. However, I am facing an issue where whatever I do in that callback function does not affect the scope. This leads me to believe that there may be conflicting scopes.
To address this, I created a directive with the following code:
angular.module('app').directive('onTextSelected', ['$window', function ($window) {
return {
restrict: 'A',
scope: {selectFn: '&'},
link: function (scope, element, attrs) {
$(element).mouseup(function () {
var selection = $window.getSelection().toString();
if ($window.getSelection().removeAllRanges) {
$window.getSelection().removeAllRanges();
} else if ($window.getSelection().empty) {
$window.getSelection().empty();
}
if (selection && selection.trim() !== "") {
scope.selectFn({
text: selection.trim()
});
}
});
}
};
}]);
This directive is implemented in the template like so:
<pre ng-bind-html="message" id="messagePre" on-text-selected
select-fn="textSelected(text)"></pre>
Here is the callback function used:
$scope.textSelected = function (text) {
console.log(text);
$scope.currentText = text;
};
While setting the text box model with $scope.textSelected
from another function works as expected, it does not work in this particular case. Despite all the code being executed (as indicated by console prints), nothing seems to happen.