angular schema form - how can I create a “total” f

2019-05-25 05:42发布

问题:

Is there a way to create a custom fieldtype in angular schema form that is able to sum other fields on the form? I've looked at directives/decorators but am not sure how to reference the fields to be summed?

回答1:

The easiest way is probably to let the user supply the keys of the fields you'd like to sum up the and watch for changes with a $watchGroup

So an example of how a form definition could look:

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

And then you need a directive in your field type sum to actually sum things up. (WARNING, untested code)

<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))
      })
    }
  }
})

You could also do a fieldset type of thing and loop through each item in the items property of the form and go from there. The sfSelect service might also be useful. Hope that helps!