Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular.js - ng-change not firing when ng-pattern is $invalid

Tags:

angularjs

I am using ng-pattern to validate some form fields, and I am using ng-change with it to watch and process any changes, however ng-change (or $scope.$watch) will only fire when the form element is in the $valid state! I'm new to angular, so I don't know how to solve this issue, although I suspect a new directive is the way to go.

How can I get ng-change to fire in both $invalid and $valid form element states, with ng-pattern still setting the form element states as before?

Html:

<div ng-app="test">   <div ng-controller="controller">     <form name="form">         <input type="text" name="textbox" ng-pattern="/^[0-9]+$/" ng-change="change()" ng-model="inputtext"> Changes: {{ changes }}     </form>      <br>     Type in any amount of numbers, and changes should increment.      <br><br>     Now enter anything that isn't a number, and changes will stop incrementing. When the form is in the $invalid state, ng-change doesn't fire.      <br><br>     Now remove all characters that aren't numbers. It will increment like normal again. When the form is in the $valid state, ng-change will fire.      <br><br>     I would like ng-change to fire even when the the form is $invalid.      <br><br>         form.$valid: <font color="red">{{ form.$valid }}</font>    </div> </div> 

Javascript:

angular.module('test', []).controller('controller', function ($scope) {     $scope.changes = 0;     $scope.change = function () {         $scope.changes += 1;     }; }); 

I have created a working JS Fiddle which shows the problem I am having.

http://jsfiddle.net/JAN3x/1/

By the way, this angular issue also seems to be relevant: https://github.com/angular/angular.js/issues/1296

like image 570
John Doe Avatar asked Jan 01 '14 04:01

John Doe


2 Answers

You can change the behavior of your input by using ng-model-options.

Just add this attribute to your input and the ng-change event will fire:

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

see: https://docs.angularjs.org/api/ng/directive/ngModelOptions

like image 111
Eugene Avatar answered Oct 02 '22 16:10

Eugene


you just need to add

 ng-model-options="{ updateOn: 'default' , allowInvalid:'true'}" 

this indicates that the model can be set with values that did not validate correctly instead of the default behaviour.

like image 31
Evon Dos Avatar answered Oct 02 '22 15:10

Evon Dos