没有发射NG-变化时NG-模式是$无效 - Angular.js [英] Angular.js - ng-change not firing when ng-pattern is $invalid

查看:228
本文介绍了没有发射NG-变化时NG-模式是$无效 - Angular.js的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的NG-模式来验证某种形式的领域,我使用它NG-改变观看和处理任何变化,但是NG-改变(或$范围。$表)只会火当表单元素在$有效状态!我是新来的角,所以我不知道如何解决这个问题,尽管我怀疑一个新的指令是要走的路。

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.

我怎样才能在这两个$无效和有效$表单元素的状态NG变火,用NG-格局依然设置表单元素的状态和以前一样?

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:

Javascript:

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

我创建了一个工作JS小提琴这说明我有这个问题。

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

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

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

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

推荐答案

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

you can write a simple directive to listen input event.

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/

这篇关于没有发射NG-变化时NG-模式是$无效 - Angular.js的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆