Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disable text selection with Angular directive

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>
like image 429
Kimchi Man Avatar asked Jul 31 '14 18:07

Kimchi Man


People also ask

How do I turn off selection text?

You can use the user-select property to disable text selection of an element. In web browsers, if you double-click on some text it will be selected/highlighted. This property can be used to prevent this.

How do I stop text from selecting CSS?

To disable text selection highlighting in Google Chrome browser using CSS just set -user-select CSS property to none. And no prefix is required for Google Chrome and Opera Browsers.

Which angular directive is used to disable an element?

The ng-disabled Directive in AngularJS is used to enable or disable the HTML elements. If the expression inside the ng-disabled attribute returns true then the form field will be disabled or vice versa.


1 Answers

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) 
}
like image 82
Polochon Avatar answered Oct 09 '22 19:10

Polochon