2014-10-01 28 views
4

如何才能使用ngTouch有選擇地禁用它適用於某些元素?也就是說,對於某些元素,我想使用原始的ngClick指令而不是ngTouch提供的指令。事情是這樣的:如何有條件地禁用ngTouch並回退到ng-click

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

回答

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}); 
       }); 
      }); 
      }; 
     } 
    }; 
}]); 

Demo


方法2: - 隨着裝飾爲NG-點擊指令

另一種方式創建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> 

Demo-Decorator