使用clipboard.js复制表行

时间:2016-06-02 14:02:30

标签: javascript angularjs clipboard.js

我有一个引导表,在其中我使用Angular的指令ng-repeat动态显示数据库搜索的结果。这些结果包括电子邮件字段。我试图在每个电子邮件单元格的右侧显示一个按钮,该按钮会将该单元格的电子邮件复制到剪贴板中。

但是该表没有唯一的ID字段,我也不知道如何为每行的电子邮件字段分配不同的ID,以便clipboard.js' "数据剪贴板对象"知道它必须复制同一行的电子邮件。现在,每个按钮都会复制第一行的电子邮件,与其自己的行无关,可能是因为它查找了第一个出现的" #emailField"标签

有什么想法吗?

这是我的html文件:

<html>
<head>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"></script>
</head>
<body ng-app="myApp">
    <div class="container" ng-controller="AppCtrl">
        <br>
        <input  type="text" class="form-control" ng-model="query" placeholder="Chercher ici">
        <br>
        <br>
        <h4>Results:</h4>
        <table class="table table-striped table-responsive table-condensed table-bordered">
            <thead>
                <tr>
                    <th>Client</th>
                    <th>Contact</th>
                    <th>Email</th>
                    <th>Telephone</th>
                    <th>Mobile</th>
                </tr>
            </thead>
            <tbody>
                <tr ng-repeat="x in queryResult">
                    <td>{{ x.client }}</td>
                    <td>{{ x.contact }}</td>
                    <td>
                        <b id="emailField">{{ x.email }}</b>
                        <button type="button" class="btn btn-default pull-right" data-clipboard-target="#emailField">
                            <span class="glyphicon glyphicon-copy"></span>
                        </button>
                    </td>
                    <td>{{ x.telephone }}</td>
                    <td>{{ x.mobile }}</td>
                </tr>
            </tbody>
        </table>
        <h4>Query status:</h4>
        <pre class="ng-binding" ng-bind="queryStatus"></pre>
    </div>

    <!-- Scripts-->
    <script src="./bower_components/clipboard/dist/clipboard.min.js"></script>
    <script>
        new Clipboard('.btn');
    </script>
    <script src="./bower_components/angular/angular.js"></script>
    <script src="./bower_components/angular-bootstrap/ui-bootstrap-tpls.js"></script>
    <script src="./bower_components/angular-ui-router/release/angular-ui-router.js"></script>
    <script src="./controller.js"></script>
</body>

1 个答案:

答案 0 :(得分:3)

尝试更改标记的这一部分:

<td>
    <b id="emailField">{{ x.email }}</b>
    <button type="button" class="btn btn-default pull-right" data-clipboard-target="#emailField">
        <span class="glyphicon glyphicon-copy"></span>
    </button>
</td>

到此:

<td>
    <b id="emailField_{{$index}}">{{ x.email }}</b>
    <button type="button" class="btn btn-default pull-right" data-clipboard-target="#emailField_{{$index}}">
        <span class="glyphicon glyphicon-copy"></span>
    </button>
</td>

您可以使用$index中提供的ng-repeat为每个电子邮件元素创建唯一ID。