You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从禁用的ui-select获取选中文本并实现双击复制功能?

解决ui-select双击复制内容的问题

我来帮你搞定这个需求!既然已经给ui-select加了disable属性,默认状态下它是无法被选中和复制的,ng-readonly之所以没用,是因为它主要针对原生表单控件,而ui-select的选中内容区域是普通的文本元素,所以得换个思路来实现双击复制。

实现步骤

核心思路是给ui-select的显示文本绑定双击事件,然后直接获取文本内容并复制到剪贴板:

  1. 给显示文本绑定双击事件
    在ui-select-match内部的文本元素上添加ng-dblclick指令,触发复制函数。

  2. 编写复制逻辑
    用现代的Clipboard API(兼容性更好)或者传统的选中复制方式,把文本内容复制到剪贴板。

完整代码示例

HTML部分

<div ng-app="boomstick" ng-controller="DemoCtrl">
  <ui-select ng-model="person.selected" theme="bootstrap" disable="true">
    <ui-select-match placeholder="Select a person...">
      <!-- 这里添加ng-dblclick绑定复制函数 -->
      <span ng-dblclick="copyContent($event)">{{$select.selected.name}}</span>
    </ui-select-match>
    <ui-select-choices repeat="person in people | propsFilter: {name: $select.search}">
      <div ng-bind-html="person.name | highlight: $select.search"></div>
    </ui-select-choices>
  </ui-select>
</div>

JavaScript部分

angular.module('boomstick', ['ui.select', 'ngSanitize'])
.controller('DemoCtrl', function($scope) {
  $scope.people = [
    { name: 'Batman' },
    { name: 'Superman' },
    { name: 'Wonder Woman' }
  ];
  $scope.person = { selected: $scope.people[0] }; // 默认选中Batman

  // 双击复制函数
  $scope.copyContent = function(event) {
    // 获取当前元素的文本内容
    const targetText = event.target.textContent.trim();
    // 使用Clipboard API复制文本
    navigator.clipboard.writeText(targetText)
      .then(() => {
        console.log('内容已复制到剪贴板');
        // 可选:给用户一个提示
        // alert('内容已复制!');
      })
      .catch(err => {
        console.error('复制失败:', err);
      });
  };
});

关键说明

  • 为什么不用ng-readonly?因为readonly是针对input、textarea这类原生表单控件的属性,ui-select的显示区域是span元素,所以这个属性不会生效。
  • 用Clipboard API比传统的document.execCommand('copy')更现代,兼容性也覆盖了主流浏览器(Chrome、Firefox、Edge等),如果需要兼容旧版浏览器,可以 fallback 到传统方式。
  • 双击事件绑定在显示文本的span上,确保只有双击选中的内容区域才会触发复制,不会影响ui-select的其他部分。

内容的提问来源于stack exchange,提问作者Gengetsu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 04:06:21