自定义表单验证指令不传递输入数据

时间:2014-06-17 09:21:09

标签: javascript forms angularjs

我编写了一个自定义表单验证指令,只检查输入的金额是否超过设定金额。如果是,则它会提醒用户,如果没有,则表示照常提交。

我遇到的问题是,当我提交表单时,控制器会将我输入的数据输入到存储中。

我明白了

{ "date": "2014-06-17T09:14:51.340Z", "status": false }

而不是

{ "amount": 1222, "date": "2014-06-17T09:14:51.340Z", "status": false }

//形式

<form name="removeMoney" ng-submit="removeEntry()" novalidate>

              <label class="error">
                <input
                  type="number"
                  name="subAmount"
                  placeholder="Remove money from wallet"
                  ng-model="subtractAmount"
                  ng-pattern="/^\d{0,9}(\.\d{1,2})?$/"
                  custom-validation />
              </label>

              <small class="error" ng-show="removeMoney.subAmount.$error.customValidation">
                You can't remove more than {{ total | currency:'£' }}
              </small>

              <small class="error" ng-show="removeMoney.subAmount.$error.pattern">
                Please enter values with no/two decimal points only -- 0.00
              </small>

              <button type="submit" ng-disabled="removeMoney.$invalid" class="button postfix alert">Remove</button>

        </form>

//控制器

$scope.removeEntry = function() {
    var date = new Date();

    $scope.walletItems.push({amount:$scope.subtractAmount, date:date, status:false});
    $scope.subtractAmount = "";
    $scope.removeMoney.$setPristine();
}

//指令

app.directive('customValidation', function() {
return {
    restrict: 'A',
    require:'ngModel',
    link: function(scope, elem, attrs, ctrl) {
        ctrl.$parsers.unshift(function(value) {
            var minimum = ctrl.$viewValue;
            if (minimum > scope.total) {
                ctrl.$setValidity('customValidation', false);
            } else {
                ctrl.$setValidity('customValidation', true);
            }
        });
    }
}
});

1 个答案:

答案 0 :(得分:0)

我没有返回该值。这就是我提交表格时没有发生任何事情的原因。

app.directive('customValidation', function() {
return {
    restrict: 'A',
    require:'ngModel',
    link: function(scope, elem, attrs, ctrl) {
        ctrl.$parsers.unshift(function(value) {
            var minimum = ctrl.$viewValue;
            if (minimum > scope.total) {
                ctrl.$setValidity('customValidation', false);
            } else {
                ctrl.$setValidity('customValidation', true);
            }
            return value;
        });
    }
}
});