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

AngularJS中如何在ngTagsInput组件内调用函数?

实现ngTagsInput的自动补全与自定义点击事件

我来帮你一步步搞定这个需求,咱们分几个核心部分来落地:

1. 基础准备

首先确保你已经正确引入了ngTagsInput的样式和脚本文件,并且在你的AngularJS模块中注入ngTagsInput依赖:

angular.module('yourInvoiceApp', ['ngTagsInput']);

2. 配置自动补全下拉框

要实现输入时匹配预设数组的自动补全,我们需要结合auto-complete指令和数据源函数:

  • 先在控制器里定义预设标签数组,以及过滤匹配的逻辑
  • 在<tags-input>标签中绑定auto-complete的数据源

控制器代码示例

angular.module('yourInvoiceApp').controller('InvoiceController', function($scope) {
    // 预设的标签数组,你可以根据业务需求修改内容
    $scope.presetTags = ['客户A', '供应商B', '项目X', '费用类型Y'];
    
    // 自动补全的数据源函数:根据用户输入过滤预设数组
    $scope.loadMatchingTags = function(query) {
        // 这里可以自定义匹配规则,比如包含匹配、开头匹配,下面是忽略大小写的包含匹配
        return $scope.presetTags.filter(tag => 
            tag.toLowerCase().includes(query.toLowerCase())
        );
    };

    // 你要触发的自定义函数
    $scope.onTagSelected = function(selectedTag) {
        // 这里写你的业务逻辑,比如请求接口、更新页面数据等
        console.log('选中的标签内容:', selectedTag.text);
        // 示例:根据选中标签加载对应账户详情
        // $scope.loadAccountInfo(selectedTag.text);
    };
});

3. 模板中的标签组件配置

把<tags-input>和<auto-complete>结合,同时绑定选中事件:

<div ng-controller="InvoiceController">
    <tags-input 
        ng-model="model.invoiceSelectedAccount" 
        placeholder="输入标签或选择预设选项"
        add-on-enter="true">
        <auto-complete 
            source="loadMatchingTags($query)"
            on-select="onTagSelected($item)">
        </auto-complete>
    </tags-input>
</div>

关键细节说明

  • source="loadMatchingTags($query)":$query是ngTagsInput自动传入的用户输入内容,我们用它过滤预设数组返回匹配结果
  • on-select="onTagSelected($item)":用户点击下拉选项时,$item会携带选中的标签对象(包含text等属性),触发自定义函数
  • 如果需要更严格的匹配(比如只匹配标签开头),可以修改loadMatchingTags函数:
$scope.loadMatchingTags = function(query) {
    return $scope.presetTags.filter(tag => 
        tag.toLowerCase().startsWith(query.toLowerCase())
    );
};

这样就能完美实现你想要的功能啦!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 08:16:05