代码之家  ›  专栏  ›  技术社区  ›  Greg Zuber

角度方向将ngmodel值更改为未定义

  •  0
  • Greg Zuber  · 技术社区  · 11 年前

    我正在使用此表单

    <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>
    

    该角度代码:

    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) {
        };
      }
    };
    });
    

    在更改输入值并单击保存后,我在$scope.testData中得到了未定义的值。为什么以及如何避免?

    我试图补充:

    scope.testData = viewValue;
    

    内部功能:

    ctrl.$validators.validators
    

    但它不起作用——只能轮流进行。

    1 回复  |  直到 11 年前
        1
  •  0
  •   noj    11 年前

    您的验证器需要返回true才能设置值,否则它将是未定义的

    如果有效性更改为无效,则模型将设置为undefined,除非ngModelOptions.allowInvalid为true。如果有效性更改为有效,它将将模型设置为最后一个可用的有效modelValue,即最后一个解析的值或从范围中设置的最后一个值。

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