Angular.js - ng-change not firing when ng-pattern is $invalid

后端 未结 4 2086
别那么骄傲
别那么骄傲 2020-12-13 06:43

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 wh

相关标签:
4条回答
  • 2020-12-13 06:53

    Edit This was answered when ng-model-options was not available. Please see the top-voted answer.

    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/

    0 讨论(0)
  • 2020-12-13 06:54

    You can change the behavior of your input by using ng-model-options.

    Just add this attribute to your input and the ng-change event will fire:

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

    see: https://docs.angularjs.org/api/ng/directive/ngModelOptions

    0 讨论(0)
  • 2020-12-13 07:00

    you just need to add

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

    this indicates that the model can be set with values that did not validate correctly instead of the default behaviour.

    0 讨论(0)
  • 2020-12-13 07:17

    Inspired by the Li Yin Kong ingenious solution :

    His solution has an issue concerning the ndModel update (see the comments of his post).

    My fix essentially changes the scope type of the directive. It lets directive access to controller scope (and methods) Then, watch-change directive does not need an "instruction to eval" (change()) anymore, but only the "name of the controller method to call" (change).

    And to get the new value of the input in this function, I pass the context (this = the input itself). So I can get the value or any property of it.

    This way, we don't care about ngModel updates (or if the form is invalid, which was another issue of the initial solution : ngModel is deleted if form is invalid)

    HTML :

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

    JAVASCRIPT :

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

    DEMO : http://jsfiddle.net/msieurtoph/0Ld5p2t4/

    0 讨论(0)
提交回复
热议问题