Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
958 views
in Technique[技术] by (71.8m points)

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...