Search code examples
angularjsangular-schema-form

Set the value of a different field when a field value changes


I'm using Angular Schema Form and I want to set a model property to null when a field value changes. I've tried using onChange in the form definition like so

{
  key: '7_11',
  type: 'radios',
  titleMap: [{value: 'no', name: 'No'}, {value: 'yes', name: 'Yes'}],

  onChange: function(modelValue,form) {
    if (!modelValue) {
      // model['8_1'] = null
    }
  }
}

Notice that the model property I'm trying to set is bound to a different field than the field that has changed

I can't do it in the manner indicated by the comment, because model is not in scope in the onChange listener.

Update

A second example is this Plunker demo. Say we want to clear the 2 checkboxes (by removing the corresponding properties from the model) whenever some text is entered in the Name field, how could this be achieved?

I should also point out that for reasons I won't bore you with, I can't implement this using a conditional and destroyStrategy.


Solution

  • Well, it is not uncommon (because it is kind of natural) to set the model and the form inside the scope of the same controller. If that is the case, you can set X by $scope.model.X = modelValue.

    Or perhaps you are in a position where you can't reach the scope of the model, in that case it is more complicated. On the other hand I would recommend to do it all in the same place.

    (Sometimes that is not possible. For example, I have dynamic forms and schemas in my application, however in those cases I use generalized functionality like the filter functionality in ASFDS or ASF conditions and avoid hard-coding UI using onChange) .

    For example, this would set foo2 if foo is changed in the plunkr:

    onChange: function(modelValue,form) {
        if (modelValue) {
            $scope.model.foo2 = ["Yes"];
        }
    },