Friday, September 29, 2017

AngularJS – disable if $pristine bug for inputs with pre-filled ng-model values

I have an input field that is pre-filled with a value from an object’s json property using ng-model, and I’m trying to disable a button if this input is either empty initially or if it has an invalid value.

This works, but when the page loads with data already in the input box as a value, the input is treated as being $pristine, because it has not been touched, even though there is a valid value. Therefore, the button, which should be enabled because of the valid value, is still disabled.

I can change the $pristine condition to (personalDetailsForm.niNumber.$pristine && personalDetailsForm.niNumber.$invalid), which correctly enables the button on load when there is a pre-filled value in the input, but if the pre-filled value is removed, the input isn’t treated as being invalid.

Is there any way around this?

HTML:

<div input-field class="input-field col-xs-12 col-sm-6 col-md-2">
    <input id="niNumberInput" name="niNumber" type="text" class="validate" pattern=".{9}" placeholder="" data-ng-model="niNumber">
    <label for="niNumberInput" data-error="National Insurance number must be 9 characters long">National Insurance Number</label>
</div>
<div input-field class="input-field col-xs-12 col-sm-6 col-md-1">
    <button data-ng-click="verifyNINumber()" data-ng-disabled="personalDetailsForm.niNumber.$invalid || personalDetailsForm.niNumber.$pristine" class="btn button waves-effect"><span class="fa fa-search"></span>Verify</button>
</div>

Source: AngularJS



from Angular Questions https://angularquestions.com/2017/09/29/angularjs-disable-if-pristine-bug-for-inputs-with-pre-filled-ng-model-values/
via @lzomedia #developer #freelance #web #lzomedia.com

No comments:

Post a Comment