programing

Angular.js - ng-pattern이 $비활성일 경우 ng-change가 실행되지 않음

mailnote 2023. 4. 6. 21:52
반응형

Angular.js - ng-pattern이 $비활성일 경우 ng-change가 실행되지 않음

ng-pattern을 사용하여 폼필드를 확인하고 ng-change를 사용하여 ng-change(또는 $scope)의 변경을 감시 및 처리합니다.$watch)는 폼 요소가 $valid 상태일 때만 실행됩니다.저는 앵글에 익숙하지 않기 때문에 이 문제를 어떻게 해결해야 할지 모르겠습니다만, 새로운 지시가 바람직한 방법이라고는 생각되지 않습니다.

ng-pattern이 이전과 같이 폼 요소 상태를 설정한 상태에서 어떻게 하면 ng-change를 $invalid 및 $valid 폼 요소 상태로 실행할 수 있습니까?

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 Fielle을 작성했습니다.

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

참고로 이 각도의 문제도 관련이 있는 것 같습니다.https://github.com/angular/angular.js/issues/1296

ng-model-options를 사용하면 입력 동작을 변경할 수 있습니다.

이 속성을 입력에 추가하면 ng-change 이벤트가 발생합니다.

      ng-model-options="{allowInvalid: true}"

참조: https://docs.angularjs.org/api/ng/directive/ngModelOptions

추가만 하면 됩니다.

 ng-model-options="{ updateOn: 'default' , allowInvalid:'true'}"

이는 기본 동작 대신 올바르게 검증되지 않은 값으로 모델을 설정할 수 있음을 나타냅니다.

[편집(Edit)]이 응답은 다음과 같습니다.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/

Li Yin Kong의 독창적인 솔루션에서 영감을 얻어:

그의 솔루션에는 ndModel 업데이트에 관한 문제가 있습니다(그의 투고 코멘트 참조).

내 수정은 기본적으로 지침의 범위 유형을 변경합니다.컨트롤러 범위(및 메서드)에 직접 액세스할 수 있습니다.그리고나서,watch-change지침에는 "평가하는 지침"이 필요하지 않습니다(change())는 종료되었지만, 「콜하는 컨트롤러 메서드의 이름」(change).

그리고 이 함수에서 입력의 새 값을 얻기 위해 컨텍스트를 전달합니다(이 = 입력 자체).그래서 나는 그것의 가치나 어떤 속성도 얻을 수 있다.

이 방법에서는 ngModel 업데이트에 관심이 없습니다(또는 초기 솔루션의 다른 문제였던 폼이 유효하지 않은 경우 ngModel이 삭제됩니다).

HTML:

<input type="text" name="textbox" ng-pattern="/^[0-9]+$/" watch-change="change" ng-model="inputtext">

자바스크립트:

app.directive('watchChange', function() {
    return {
        restrict : 'A',
        link: function(scope, element, attrs) {
            element.on('input', function(){
                scope[attrs.watchChange](this);
            })
        }
    };
});

데모: http://jsfiddle.net/msieurtoph/0Ld5p2t4/

언급URL : https://stackoverflow.com/questions/20865507/angular-js-ng-change-not-firing-when-ng-pattern-is-invalid

반응형