7

After reading quite a few posts I decided that this ought to work:

vm.model.myChange = function(element) {
  console.log(element);
}

.. and in the vm.fields:

{
"key": "transportation",
"type": "select",
"templateOptions": {
  "label": "How do you get around in the city",
  "valueProp": "name",
  "onChange": "model.myChange()", // ADDED
  "options": [{
    "name": "Car"
  }, {
    "name": "Helicopter"
  }]
}

In practice this has no effect, i.e. my function is not called. The generated form contained no reference to my function either.

I could not find a working example of how to do this. Any suggestions?

Thx. Paul

user1712240
  • 131
  • 1
  • 2
  • 8

2 Answers2

5

you can do any of these three things:

templateOptions: {
   onChange: function($viewValue, $modelValue, $scope) {
   //implement logic here
   };
}

OR

templateOptions: {
   onChange: callMe()
},
controller: function($viewValue, $modelValue, $scope) {
    $scope.callMe = function() {
    //implement logic here
    };
}

OR

    templateOptions: {
       onChange: ''
    },
    expressionProperties : {
       'templateOptions.onChange': function($viewValue, $modelValue, $scope) {
       //implement logic here
       };
   }
MattE
  • 1,044
  • 1
  • 14
  • 34
  • This (the first option) did not do anything for me; I'm new to formly but I imagine it has something to do with the specific `templateOptions` available in whatever template one happens to be using? Using `change` instead of `onChange`, as shown here https://stackoverflow.com/a/59791792/2442167 did work for me. – mactyr Feb 24 '21 at 15:05
3

One way I handled this is having my json fields served from a service.With this one can comfortably call a function.

NB:This is served from a service or a factory

var getFields = function () {
    var fields = [
        {
           "key": "transportation",
           "type": "select",
           "templateOptions": {
           "label": "How do you get around in the city",
           "valueProp": "name",
           "onChange": "function(){//Implement your logic}"
           "options": [{
                "name": "Car"
           }, {
             "name": "Helicopter"
           }]
       }
   ] 
};
CDan mbugua
  • 71
  • 1
  • 5