angular 模式表单 - 如何创建 "total" 字段

angular schema form - how can I create a "total" field

有没有办法在 angular 模式表单中创建自定义字段类型,以便对表单上的其他字段求和?我查看了 directives/decorators 但不确定如何引用要求和的字段?

最简单的方法可能是让用户提供您想要总结的字段的键,并使用 $watchGroup

观察变化

表单定义的外观示例:

{
  type: "sum",
  sumFields: [
    "key.to.field1",
    "key.to.field2",
    "key.to.field3"
  ]
}

然后您需要在您的字段类型 sum 中使用一个指令来实际求和。 (警告,未经测试的代码)

<div class="form-control-group"> 
  <input disabled sum-it-up="form.sumFields" type="text">
</div>


angular.module('myModule').directive('sumItUp',function(){
  return {
    scope: true,
    link: function(scope, element, attr) {
      var keys = scope.$eval(attrs.sumItUp);.map(function(key){
         // Whatever you put in model is always available on scope
         // as model. Skipped ObjectPath for simplification.
         return 'model.'+key 
      }) 
      scope.$watchGroup(keys, function(values) {
        element.value(values.reduce(function(sum, value){ 
          return sum+value
        },0))
      })
    }
  }
})

您也可以做一个字段集类型的事情,循环遍历表单 items 属性 中的每个项目,然后从那里开始。 sfSelect 服务也可能有用。希望对您有所帮助!