Angular - ng-change not firing when ng-model is changed

后端 未结 4 1653
伪装坚强ぢ
伪装坚强ぢ 2020-12-15 19:17

The input is the following:


The action() is exe

相关标签:
4条回答
  • 2020-12-15 19:30

    ngChange is just for the input, if you want to listen the model do like this

    $scope.$watch('repair.test', function(newvalue,oldvalue) {
    
                });
    
    0 讨论(0)
  • 2020-12-15 19:33

    You can use a watcher-function in your controller

    $scope.$watch('repair.test', function() {
        $scope.action();
    });
    
    0 讨论(0)
  • 2020-12-15 19:46

    The ngChange expression is only evaluated when a change in the input value causes a new value to be committed to the model.

    It will not be evaluated:

    • if the value returned from the $parsers transformation pipeline has not changed
    • if the input has continued to be invalid since the model will stay null
    • if the model is changed programmatically and not by a change to the input value

    Try to create a watcher using $scope.$watch - $watch(watchExpression, listener, [objectEquality]);

    Example

    $scope.$watch('repair.test', function(newValue, oldValue) {
        // ...
    });
    
    0 讨论(0)
  • 2020-12-15 19:52

    Another solution would be to use a directive that watched the model for any changes instead of using ng-change.

    app.directive('onModelChange', function($parse){
        return {
            restrict: "A",
            require: "?ngModel",
            link: function(scope, elem, attrs, ctrl) {
                scope.$watch(attrs['ngModel'], function (newValue, oldValue) {
                    if (typeof(newValue) === "undefined" || newValue == oldValue) {
                        return;
                    }
                    var changeExpr = $parse(attrs['onModelChange']);
                    if (changeExpr) {
                        changeExpr(scope);
                    }
                });
            } 
        };
    });
    

    Then you would use it like so:

    <input class="value" type="text" ng-model="myVar" on-model-change="doSomething(myVar)"/>
    
    0 讨论(0)
提交回复
热议问题