简体   繁体   中英

Angular directive change ngmodel value to undefined

I'm using this form

<div ng-controller="TestController">
    <form ng-submit="saveForm()">
        <input type="text" name="test" ng-model="testData" test="{{testValue}}"/>
        <input type="submit" value="Save"/>
    </form>
</div>

and this angular code:

app.controller('TestController', [ '$scope', function($scope) {
    $scope.testData="testValue";

    $scope.saveForm = function(){
        console.log($scope.testData);
    }

}]);

app.directive('test', function($parse) {
return {
  require: 'ngModel',
  link: function(scope, elm, attrs, ctrl) {
    ctrl.$validators.validators = function(modelValue, viewValue) {
    };
  }
};
});

And after changing value in input and clicking save I'm getting undefined value in $scope.testData. Why and how to avoid that?

I was trying to add:

scope.testData = viewValue;

inside function:

ctrl.$validators.validators

But it doesn't work - only by turns.

Your validator needs to return true for the value to be set, otherwise it will be undefined

If the validity changes to invalid, the model will be set to undefined, unless ngModelOptions.allowInvalid is true. If the validity changes to valid, it will set the model to the last available valid modelValue, ie either the last parsed value or the last value set from the scope.

ctrl.$validators.validators = function(modelValue, viewValue) {
    return modelValue !== '';
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM