简体   繁体   English

Angular指令将ngmodel值更改为undefined

[英]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. 在更改输入值并单击保存后,我在$ 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 您的验证程序需要为要设置的值返回true,否则它将是未定义的

If the validity changes to invalid, the model will be set to undefined, unless ngModelOptions.allowInvalid is true. 如果有效性更改为无效,则除非ngModelOptions.allowInvalid为true,否则模型将设置为undefined。 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. 如果有效性更改为有效,它将把模型设置为最后一个可用的有效modelValue,即最后解析的值或从范围设置的最后一个值。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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