Martin Locqueville Martin Locqueville - 6 months ago 86
AngularJS Question

Copy table row using clipboard.js

I have a bootstrap table in which I dynamically display the results of a database search, using Angular's directive ng-repeat. Those results include an email field. I'm trying to display a button to the right of each email cell that would copy the email of that cell into the clipboard.

But that table has no unique Id field, and I don't know how to assign a different id to each row's email field, so that clipboard.js' "data-clipboard-target" knows it has to copy the email of the same row. Right now, every button copies the first row's email, independently of its own row, probably because it looks up the first appearance of the "#emailField" tag.

Any ideas ?

Here's my html file:

<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>



Lex Lex
Answer

Try changing this section of markup:

<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>

to this:

<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>

You can use the $index that is available inside ng-repeat to create a unique id for each email element.

Comments