一尘不染

Angular.js-ng-pattern为$ invalid时不触发ng-change

angularjs

我正在使用ng-pattern来验证某些表单字段,并且正在使用ng-change来监视和处理任何更改,但是ng-change(或$ scope。$
watch)仅在form元素位于$有效状态!我对angular还是陌生的,所以我不知道如何解决这个问题,尽管我怀疑应该采用新的指令。

在ng-pattern仍然像以前一样设置表单元素状态的情况下,如何在$ invalid和$ valid表单元素状态下触发ng-change?

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;
    };
});

我创建了一个工作的JS小提琴,它显示了我遇到的问题。

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

顺便说一下,这个角度问题似乎也很相关:https
:
//github.com/angular/angular.js/issues/1296


阅读 295

收藏
2020-07-04

共1个答案

一尘不染

编辑 回答ng-model-options不可用时。请查看投票最多的答案。

您可以编写一个简单的指令来监听input事件。

HTML:

<input type="text" name="textbox" ng-pattern="/^[0-9]+$/" watch-change="change()" ng-model="inputtext"> Changes: {{ changes }}

JS:

app.directive('watchChange', function() {
    return {
        scope: {
            onchange: '&watchChange'
        },
        link: function(scope, element, attrs) {
            element.on('input', function() {
                scope.$apply(function () {
                    scope.onchange();
                });
            });
        }
    };
});

http://jsfiddle.net/H2EAB/

2020-07-04