Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
157
rated 0 times [  159] [ 2]  / answers: 1 / hits: 12006  / 10 Years ago, thu, july 31, 2014, 12:00:00

I am learning JavaScript and AngularJS.



I want to disable text selection with Angular Directive.



I have a JavaScript code for that function:



function clearSelection() {
if(document.selection && document.selection.empty) {
document.selection.empty();
}
else if(window.getSelection) {
var sel = window.getSelection();
sel.removeAllRanges();
}
};


And I am working on the directive, but don't know how to add that function to the directive.



Directive:



...
.directive('disableTextSelection', function() {
return {
link: function($scope, $element, $attrs) {
// Something here..
}
}
}
...


And I want to do this in HTML like:



<table disable-text-selection>
...
</table>

More From » angularjs

 Answers
20

AngularJS and more globally JavaScript are not the good thing to do that.



You should use a CSS property like this one



.disable-text-selection {
-webkit-touch-callout: none;
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}


EDIT



Angular directives are usually used to modify the DOM or add some features like many jQuery plugins, not bind a function to a DOMnode (or use ng-click in this case).



Your function can clear a selection on IE but you must bind an event to active it.



Anyway, in your case you should use the second parameter provided in the link function (called after compile and all controllers declarations) and bind it to your function calling.



link: function($scope, $element, $attrs) { 
$element.bind('click', clearSelection)
}

[#43446] Wednesday, July 30, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
andreguym

Total Points: 125
Total Questions: 112
Total Answers: 103

Location: Wallis and Futuna
Member since Tue, Mar 30, 2021
3 Years ago
;