So, what I want is a custom directive which will read and clear the current selection, and then pass the selected text to a callback function. This works, but whatever I do in that callback function has no effect on the scope, which leads me to believe that there are multiple scopes, which are in conflict somehow.
First, I defined a directive like this:
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()
});
}
});
}
};
}]);
It's used in the template as follows:
<pre ng-bind-html="message" id="messagePre" on-text-selected
select-fn="textSelected(text)"></pre>
And this is the callback function:
$scope.textSelected = function (text) {
console.log(text);
$scope.currentText = text;
};
I have a text box which uses $scope.textSelected
as model, and setting it with the same code from another function works properly, but in this case it just doesn't. Nothing happens, although all the code gets executed (it prints on the console, for example).
It works after calling
$scope.$digest()
or using
$scope.$apply()
Probably related to the usage of jQuery here.