Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing `ng-required` calls `ng-change`

I have a strange behavior in my app using AngularJS 1.5.8:

plunker (https://plnkr.co/edit/zaHVJeK8hdxk2gaOL9Pf?p=preview) and video(http://recordit.co/eszvfdfC9S)

  • step 1. At the beginning changing ng-required doesn't call ng-change function
  • step 2. After making changes in input AND removing them (input is empty) ng-required DOES call ng-change function

expected behavior?

  • step 2. After making changes in input AND removing them (input is empty) ng-required SHOULD NOT call ng-change function. As it was at the beginning, and as it is when input has some value

Please let me know if it's a bug or not. If not then why changing ng-required calls ng-change NOT always or even at all?

ANSWER IS FOUND-------------------------------------------------------------------------------------------------------

NgModelController has two properties: $viewValue (value entered by user) and $modelValue (value bound to your model). When the value entered by the user fails validation, NgModelController sets the model to undefined.

In AngularJS 1.3, they added the ng-model-options directive. It lets you configure how/when the model gets updated. You can use the allowInvalid option to prevent your model from being set to undefined:

ng-model-options="{allowInvalid: true}"
like image 665
Ivan Avatar asked Nov 24 '16 08:11

Ivan


1 Answers

You should add

        ng-model-options="{allowInvalid: true}"

So the final result will be

<input type="text" 
    ng-change="$ctrl.onChange()" 
    ng-required="$ctrl.isRequired"
    ng-model-options="{allowInvalid: true}"
    ng-model="$ctrl.val"
    />
like image 160
user2414751 Avatar answered Sep 20 '22 00:09

user2414751