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

如何为$uibModal弹窗内的按钮绑定除$dismiss()外的自定义函数

实现方案

方案1:通过resolve+controller传递自定义函数(推荐)

该方案耦合度低,符合AngularJS编码规范,适合绝大多数场景:

// 提前定义你需要调用的自定义函数
const yourCustomFn = () => {
  // 此处写你自己的业务逻辑
  console.log('自定义函数触发成功')
}

const modalInstance = $uibModal.open({
  animation: this.animationsEnabled,
  ariaLabelledBy: 'modal-title',
  ariaDescribedBy: 'modal-body',
  template: [
      '<div class="modal-content">',
      '<div class="modal-header">',
      '<h3 class="modal-title">Regulamin</h3>',
      '</div>',
      '<div class="modal-body">',
      '$1. Give us all your money!',
      '</div>',
      '<div class="modal-footer">',
      '<button class="btn btn-primary" ng-click="$ctrl.testing()">TESTING</button>',
      '</div>',
      '</div>'
    ].join(''),
  size: 'md',
  // 新增resolve参数传递自定义函数
  resolve: {
    customFn: () => yourCustomFn
  },
  // 新增弹窗专属controller绑定方法
  controller: function(customFn, $uibModalInstance) {
    const $ctrl = this
    $ctrl.testing = () => {
      // 调用传入的自定义函数
      customFn()
      // 若调用完需要关闭弹窗可加下一行,不需要可删除
      // $uibModalInstance.dismiss()
    }
  },
  controllerAs: '$ctrl'
})

方案2:直接传入当前作用域(适合快速实现)

如果不需要拆分太细,可直接把当前上下文的作用域传递给弹窗,无需额外定义controller:

// 当前作用域下提前定义好testing方法
this.testing = () => {
  // 此处写自定义业务逻辑
  console.log('自定义函数触发成功')
  // 同样需要关闭弹窗可调用 modalInstance.dismiss()
}

const modalInstance = $uibModal.open({
  animation: this.animationsEnabled,
  ariaLabelledBy: 'modal-title',
  ariaDescribedBy: 'modal-body',
  template: [
      '<div class="modal-content">',
      '<div class="modal-header">',
      '<h3 class="modal-title">Regulamin</h3>',
      '</div>',
      '<div class="modal-body">',
      '$1. Give us all your money!',
      '</div>',
      '<div class="modal-footer">',
      '<button class="btn btn-primary" ng-click="$ctrl.testing()">TESTING</button>',
      '</div>',
      '</div>'
    ].join(''),
  size: 'md',
  // 传入当前作用域
  scope: this,
  controllerAs: '$ctrl'
})

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 07:00:04