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

后端 未结 4 2108
别那么骄傲
别那么骄傲 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 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 :

    
    

    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/

提交回复
热议问题