如何有条件地禁用ngTouch并回退到ng-click

How to disable ngTouch conditionally and fallback to ng-click

本文关键字:回退 ng-click ngTouch 有条件      更新时间:2023-09-26

如何使用ngTouch,但对某些元素选择性禁用?也就是说,对于某些元素,我希望使用原始的ngClick指令,而不是ngTouch提供的指令。类似这样的东西:

 <button ng-click-original="myClickFn()">click me</button>

问题是,一旦在依赖项中包含ngTouch模块,其版本的ngClick ngTouch.directive('ngClick'将覆盖angular core的原始ngClickDirective。因此,所有的点击都将由ngTouch的ng-click版本处理,因此您需要在模块中装饰ngCLick来处理您的场景。我可以在这里想出几个方法:-

方法1-创建自己的指令

创建一个ng-click-orig怎么样?可能不要在它前面加ng,因为它是一个自定义指令。

.directive('ngClickOrig', ['$parse', function($parse) {
      return {
        compile: function($element, attr) {
          var fn = $parse(attr["ngClickOrig"]);
          return function handler(scope, element) {
            element.on('click', function(event) {
              scope.$apply(function() {
                fn(scope, {$event:event});
              });
            });
          };
        }
     };
 }]);

演示


方法2:-使用ng-Click指令的装饰器

另一种方法是在ngClickDirective上创建一个装饰器,查找特定的属性,比如notouch,并执行定期单击或使用ngTouch提供的原始属性。

.config(function($provide){
   //Create a decoration for ngClickDirective   
   $provide.decorator('ngClickDirective', ['$delegate','$parse', function($delegate, $parse) {
        //Get the original compile function by ngTouch
        var origValue = $delegate[0].compile();
        //Get set the compiler
        $delegate[0].compile = compiler;
        //return augmented ngClick
        return $delegate;
       /*Compiler Implementation*/
       function compiler(elm, attr){
          //Look for "notouch" attribute, if present return regular click event, 
          //no touch simulation
          if(angular.isDefined(attr.notouch)){
            var fn = $parse(attr["ngClick"]);
            return function handler(scope, element) {
              element.on('click', function(event) {
                scope.$apply(function() {
                  fn(scope, {$event:event});
                });
              });
            }
          }
          //return original ngCLick implementation by ngTouch
          return origValue;
         }
   }]);
});

就像注释装饰器在第一次使用指令之前不会运行一样,它只运行一次

示例用法:-

   <button ng-click="myClickFn()" notouch>click me</button> <-- see notouch attribute -->
   <button ng-click="myClickFnTouch()">click me</button>

演示装饰器