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

Angular-Formly:选中下拉选项时设置对应输入字段为必填项

实现每组下拉框与输入框的独立必填联动(Angular-Formly)

你已经离正确实现很近了!问题核心在于对Angular-Formly表单实例上下文的理解——每个formly-form在ng-repeat里绑定的是单独的supplier对象,完全不需要依赖$index来区分组,直接用当前表单的model就能精准控制该组的字段规则。

解决方案代码

直接修改你的字段配置,确保agreementReference的必填规则只关联当前组的exportSupplier值:

vm.exportSuppliers = [{ exportSupplier: '', agreementReference: '' }];

vm.exportSupplierFields = [
  {
    fieldGroup: [
      {
        className: 'col-xs-6',
        key: 'exportSupplier',
        type: 'select2',
        templateOptions: {
          label: 'Export Supplier',
          required: false,
          options: [], // 记得填充你的下拉选项数据
          onChange: function() {
            vm.addExportSupplier();
          }
        }
      },
      {
        className: 'col-xs-5',
        key: 'agreementReference',
        type: 'input',
        templateOptions: {
          label: 'Agreement Reference',
          onChange: function() {
            vm.addExportSupplier();
          }
        },
        // 关键:仅根据当前组的exportSupplier状态设置必填
        expressionProperties: {
          'templateOptions.required': '!!model.exportSupplier'
        }
      }
    ]
  }
];

vm.addExportSupplier = function() {
  const lastGroup = vm.exportSuppliers[vm.exportSuppliers.length - 1];
  // 只有最后一组有内容时才新增空组,避免冗余空项
  if (lastGroup.exportSupplier || lastGroup.agreementReference) {
    vm.exportSuppliers.push({ exportSupplier: '', agreementReference: '' });
  }
};

HTML部分保持你的原有代码即可:

<div ng-repeat="supplier in vm.exportSuppliers" class="row">
  <formly-form 
    model="supplier" 
    fields="vm.exportSupplierFields" 
    form="vm.informationExportSupplier.form" 
    index="$index">
  </formly-form>
</div>

为什么这样能解决问题?

  • 每个formly-form实例的model都是ng-repeat循环中当前的supplier对象,完全独立于其他组。
  • !!model.exportSupplier会判断当前组的下拉框是否有选中值(非空字符串),如果有则自动将该组的agreementReference设为必填;取消选中后,必填规则会自动失效。
  • 多组情况下,每组的规则互不干扰,完全符合你“只有选中下拉框的组才要求输入框必填”的需求。

测试建议

  1. 单组测试:选中下拉框,输入框会触发必填验证;取消选中,验证消失。
  2. 多组测试:选中其中一组的下拉框,只有该组的输入框会被标记为必填,其他未选中的组不受影响。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 09:24:49