AngularJS: ng-click and select text

In my application, I use some logic after clicking on an element.

For example:

HTML

<h3 ng-click="showAlert('text')">this is text! (try to click and select)</h3>

Js

$scope.showAlert = function(text) {
  console.log('click!');
};

and when I click on an element: everything is fine. Everything is done as expected.

But!

Why, when I try to select text, does my event fire too?

How to skip the select event?

enter image description here

plunker: click

+4
source share
1 answer

You can get the time between mousedownand mouseupto determine if a click or text is selected.

Also: Demo

(function(){
  angular.module("app", []);

  angular.module("app")
  .directive("noclick", function(){
    return {
      restrict: "A",
      link: function(scope, element, attr){
        scope.time= Date.now();

        element.on("mousedown mouseup", function(e){
          if(e.type == "mousedown"){
            scope.time= Date.now();
          }

          if(e.type == "mouseup"){
            if(Date.now() - scope.time> 300){
              return false;
            }else{
              console.log("clicked");
            }
          }
        });
      }
    }
  });
})(window, angular);

Note. I use the directive for this case.

+4
source

Source: https://habr.com/ru/post/1615247/


All Articles