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

Joh*_*Doe 33 angularjs

我正在使用ng-pattern来验证某些表单字段,并且我正在使用ng-change来监视和处理任何更改,但是ng-change(或$ scope.$ watch)只会在表单元素位于$有效状态!我是棱角分明的,所以我不知道如何解决这个问题,虽然我怀疑新的指令是要走的路.

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

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>
Run Code Online (Sandbox Code Playgroud)

使用Javascript:

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

我创建了一个工作的JS Fiddle,它显示了我遇到的问题.

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

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

Eug*_*ene 71

您可以使用ng-model-options更改输入的行为.

只需将此属性添加到您的输入中,ng-change事件将触发:

      ng-model-options="{allowInvalid: true}"
Run Code Online (Sandbox Code Playgroud)

请参阅:https://docs.angularjs.org/api/ng/directive/ngModelOptions

  • 那是不对的.`ng-pattern`对我来说仍然正常. (2认同)

小智 15

你只需要添加

 ng-model-options="{ updateOn: 'default' , allowInvalid:'true'}"
Run Code Online (Sandbox Code Playgroud)

这表示可以使用未正确验证的值而不是默认行为来设置模型.


Luc*_*ius 5

编辑ng-model-options没有时,答案已得到解答.请参阅最高投票的答案.

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

HTML:

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

JS:

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

http://jsfiddle.net/H2EAB/

  • 我使用了这个函数,因为即使在$ invalid状态下我也需要处理一些更改,但是我注意到模型也没有更新.对于其他人,请查看`$ scope.form.element.$ viewValue`变量,该变量应该有效.如果它有一个奇怪的滞后(它对我来说),那么创建一个没有范围的新指令,`require:'ngModel'`,而不是`scope.onchange();`上面,使用`ngModel.$ setViewValue( element [0] .value);`,然后将模型fixer属性放入元素中. (2认同)