复制到剪贴板按钮HTML Angular

时间:2016-04-05 17:26:00

标签: angularjs button clipboard

假设我们有以下

<div class="echo" id="hidden_div" style="display:none">
    <pre>
       I want to copy this 
       I want to copy this 
       I want to copy this
    </pre>
</div>

假设我们有以下按钮:

<button type="button" class="btn" onclick="showHide()">Submit</button>

<script>
function showHide() {
  document.getElementById("hidden_div").style.display = "block";
}
</script>

如何创建另一个按钮以将<pre>内的值复制到剪贴板?

如何更改&#34;提交&#34;的标签?按钮到&#34;关闭&#34;并再次隐藏div,直到再次点击&#34;提交&#34;?

1 个答案:

答案 0 :(得分:2)

您可以使用ngclipboard。这是实现复制到剪贴板的简单方法。

将其包含在您的文档中。

<script src="https://cdn.rawgit.com/zenorocha/clipboard.js/master/dist/clipboard.min.js"></script>

ngclipboard依赖项添加到您的模块

var myApp = angular.module('app', ['ngclipboard']);

然后简单地使用它。这是一个例子:

<!-- Target -->
<input id="foo" value="https://github.com/sachinchoolur/ngclipboard.git">

<!-- Trigger -->
<button class="btn" ngclipboard data-clipboard-target="#foo">
    <img src="assets/clippy.svg" alt="Copy to clipboard">
</button>

在你的情况下例如:

<div class="echo" id="hidden_div" style="display:none">
    <pre id="toCopy">
         I want to copy this 
         I want to copy this 
         I want to copy this
    </pre>
</div>
<button class="btn" ngclipboard data-clipboard-target="#toCopy" ng-click="submit()">
    {{buttonText}}
</button>

在控制器代码中:

$scope.buttonText = "Submit";
$scope.submit = function(){
    if($scope.buttonText === "Submit"){
        document.getElementById("hidden_div").style.display = "block";
        $scope.buttonText = "Cancel";
    }
    else if($scope.buttonText === "Cancel"){
        document.getElementById("hidden_div").style.display = "none";
        $scope.buttonText = "Submit";
    }
}

没有测试过这个。但这应该有效。在这两种情况下,请告诉我。