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

你离开我真会死。 提交于 2019-12-22 13:54:06

问题


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!



来源:https://stackoverflow.com/questions/29026254/angular-schema-form-how-can-i-create-a-total-field

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!