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

前端之家收集整理的这篇文章主要介绍了angularjs – 当ng-pattern为$invalid时,Angular.js – ng-change不触发前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我使用ng-pattern来验证一些表单字段,我使用ng-change来观察和处理任何更改,但是ng-change(或$ scope。$ watch)只会在表单元素位于$ valid state!我是新的角,所以我不知道如何解决这个问题,虽然我怀疑一个新的指令是要走的路。

如何获得ng-change在$ invalid和$ valid表单元素状态中触发,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>

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

你可以写一个简单的指令来监听输入事件。

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/

原文链接:https://www.f2er.com/angularjs/145443.html

猜你在找的Angularjs相关文章