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

4

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

 <button ng-click-original="myClickFn()">click me</button>
1个回答

9
问题在于,一旦在依赖项中包含ngTouch模块,它的版本ngClickngTouch.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>

演示-装饰器


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接