2016-06-25 10 views
-2

ボタンをクリックするとJavaScript関数が入力フィールドからクリップボードにテキストをコピーします。JavaScript関数をAngularJSディレクティブに変換する方法は?

<script type="text/javascript"> 
    (function() { 
     'use strict'; 
     // click events 
     document.body.addEventListener('click', copy, true); 
     // event handler 
     function copy(e) { 
      // find target element 
      var 
       t = e.target, 
       c = t.dataset.copytarget, 
       inp = (c ? document.querySelector(c) : null); 
      // is element selectable? 
      if (inp && inp.select) { 
       // select text 
       inp.select(); 
       try { 
        // copy text 
        document.execCommand('copy'); 
        inp.blur(); 
       } 
       catch (err) { 
        alert('please press Ctrl/Cmd+C to copy'); 
       } 
      } 
     } 
    })(); 
</script> 

使用法::私はこれを試してみた

<button id="CopyTextBtn" autofocus 
     type="submit" 
     class="uui-button lime-green" 
     data-copytarget="#ClientsURL" 
     ng-click="closeThisDialog('Cancel')"> 
    Copy 
</button> 

:それは、次のようになります

appModule.directive('data-copytarget', function() { 
    return { 
     scope: {}, 
     link: function (scope, element) 
     { 
      // click events 
      document.body.addEventListener('click', copy, true); 
      // event handler 
      function copy(e) { 
       // find target element 
       var 
        t = e.target, 
        c = t.dataset.copytarget, 
        inp = (c ? document.querySelector(c) : null); 
       // is element selectable? 
       if (inp && inp.select) { 
        // select text 
        inp.select(); 
        try { 
         // copy text 
         document.execCommand('copy'); 
         inp.blur(); 
        } 
        catch (err) { 
         alert('please press Ctrl/Cmd+C to copy'); 
        } 
       } 
      } 
     } 
    }; 
}); 

しかし、それは動作しません。

+2

※「技術的に問題ありません」とは、適切な技術的な問題ではありません。それに少しの努力をしてください。 See [ask] – charlietfl

+0

もちろん私はそれをやった。 – tesicg

+0

?何をしたの?トラブルシューティング情報を適切に記述するために何の努力もしていませんでした – charlietfl

答えて

0

link関数の引数としてscope、element、attrsがありますが、elem.bind('click', function() { })を使用しないでください。angular.element(document).find('body');を使用し、clickイベントをバインドしてください。

appModule.directive('data-copytarget', function() { 
    return { 
     scope: {}, 
     link: function (scope, elem) 
     { 
      // click events 
      elem.bind('click', function() { 
       // find target element 
       var 
        t = e.target, 
        c = t.dataset.copytarget, 
        inp = (c ? document.querySelector(c) : null); 
       // is element selectable? 
       if (inp && inp.select) { 
        // select text 
        inp.select(); 
        try { 
         // copy text 
         document.execCommand('copy'); 
         inp.blur(); 
        } 
        catch (err) { 
         alert('please press Ctrl/Cmd+C to copy'); 
        } 
       }     
     } 
    }; 
}); 
+0

残念ながら、動作しません。ディレクティブは、テキストを入力フィールドからクリップボードにコピーする必要があります。 – tesicg

+0

興味深いことに、ボタンクリックのプログラムフローは指示にまったく入りません。 – tesicg

関連する問題