AngularJS DataTable中renderWith生成按钮的ng-click事件不触发如何解决
问题原因
你通过renderWith方法动态拼接生成的按钮DOM,没有经过AngularJS的编译流程,ng-click这类Angular内置指令不会被识别和绑定作用域,所以点击事件无法触发。
修改步骤
- 首先在你的控制器中注入
$compile服务,用来编译动态生成的DOM元素 - 给你的表格标签添加唯一ID,方便后续选中元素,比如:
<table id="approvalTable" datatable dt-options="dtOptions" dt-columns="dtColumns"></table>
- 修改
dtOptions中的drawCallback回调,每次表格渲染完成后,对动态生成的按钮元素做编译绑定 - 可以直接在
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
相关产品推荐
相关产品推荐

