You need to enable JavaScript to run this app. AngularJS DataTable中renderWith生成按钮的ng-click事件不触发如何解决
优惠活动
大模型
产品
解决方案
定价
更多

AngularJS DataTable中renderWith生成按钮的ng-click事件不触发如何解决

问题原因

你通过renderWith方法动态拼接生成的按钮DOM,没有经过AngularJS的编译流程,ng-click这类Angular内置指令不会被识别和绑定作用域,所以点击事件无法触发。

修改步骤
  1. 首先在你的控制器中注入$compile服务,用来编译动态生成的DOM元素
  2. 给你的表格标签添加唯一ID,方便后续选中元素,比如:
<table id="approvalTable" datatable dt-options="dtOptions" dt-columns="dtColumns"></table>
  1. 修改dtOptions中的drawCallback回调,每次表格渲染完成后,对动态生成的按钮元素做编译绑定
  2. 可以直接在ng-click中传入当前行的traceId,满足你传递行ID的需求
修改后的完整代码
// 注意控制器要注入$compile,示例:.controller('你的控制器名', function($scope, $compile, DTOptionsBuilder, DTColumnBuilder) {
$scope.dtOptions = DTOptionsBuilder.newOptions()
        .withOption('ajax', {
            dataType: 'json',
            contentType: "application/json; charset=utf-8",
            url: appConfig.apiUrl + "/approvalList?reqTraceId=" + $scope.requestApprovalId,
            xhrFields: { withCredentials: true },
            type: 'POST',
            data: function (d) {
                return JSON.stringify(d);

            },
            error: function (response) {
                ajaxErrorHandler.handle(response);
            }
        })

        .withDataProp('data')
        .withOption('processing', true)
        .withOption('serverSide', true)
        .withOption('scrollY', '400px')
        .withOption('scrollX', '100%')
        .withOption('scrollCollapse', true)
        .withOption('drawCallback', function (settings) {
            // 编译动态生成的带ng-click的元素,绑定当前scope
            $compile(angular.element('#approvalTable').find('button[ng-click]'))($scope);
        });

    $scope.dtColumns = [
        DTColumnBuilder.newColumn('traceId').withTitle('Trace ID').withClass('cus-id'),
        DTColumnBuilder.newColumn('approval.0.usr').withTitle('Name').withClass('cus-id'),
        DTColumnBuilder.newColumn('approval.0.threshold').withTitle('Match Strength %').withClass('cus-id'),
        DTColumnBuilder.newColumn('traceId').withTitle('Action').renderWith(function (data, type, full) {
            // 这里把traceId作为参数传入passId,字符串类型要加转义的单引号包裹
            return '<div class="btn-group-xs">' +
                '  <button type="button" class="btn btn-flat btn-xs btn-success" ng-click="passId(\''+ data +'\');">' +
                '    <i class="ion ion-eye"></i>' +
                '  </button>' +
                '</div>';
        }).withClass('text-center').notSortable()
    ];

// 测试函数可以接收行ID参数
$scope.passId= function (traceId) {
    alert("触发成功,当前行ID为:" + traceId)
};

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.21 15:24:03