小编典典

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

angularjs

如何使用 ngTouch, 但对某些元素 有选择地禁用
它?也就是说,对于某些元素,我想使用原始ngClick指令,而不是ngTouch提供的指令。像这样:

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

阅读 251

收藏
2020-07-04

共1个答案

小编典典

问题是,一旦您将ngTouch模块包含在依赖项中,其版本ngClick
ngTouch.directive('ngClick'将覆盖角核的原始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>

演示装饰器

2020-07-04