Giovanni Far Giovanni Far - 4 months ago 47
AngularJS Question

ngChange on input changed by a select

I have a simple select input field where the user can choose an option:

<select class="form-control" id="calc-masterbatchCode"
ng-options="masterbatch as masterbatch.code for masterbatch in masterbatches"
ng-model="$parent.materialTAB.selectedMasterbatch">
</select>


as you can see the
selectedMasterbatch
object is stored in a parent controller.

Then i have a disabled input field in the order to show the property of the
selectedMasterBatch
:

<input type="text" class="form-control" id="calc-masterbatchPercentage"
ng-model="$parent.materialTAB.selectedMasterbatch.percentage"
ng-change="onMasterbPercentageChange()">


It works, but the problem is the
ngChange
directive:

because it doesn't fire the
onMasterbPercentageChange
function when the user select another masterbatch.

The only way to fire that function is to type something manually into the
calc-masterbatchParcentage
input field.

My goal is:

the user select a masterbatch, then he can see the masterbatch's property (the percentage) into the disabled input field and, when this one change, the
onMasterbPercentageChange
function is fired.

enter image description here

Answer

ngChange directive doesn't work on disable/readonly inputs, because it's only evaluated when a change in the input value causes a new value to be committed to the model. So, since you're changing the value programmatically and not typing anything to this model, it doesn't calls ngChange

Here is more one part extracted from docs:

    ngChange will not be evaluated:

  • if the value returned from the $parsers transformation pipeline has not changed
  • if the input has continued to be invalid since the model will stay null
  • if the model is changed programmatically and not by a change to the input value
  • So, to achieve what you want you must move your ng-change to your <select>.

    I hope it helps.