繁体   English   中英

AngularJS 自定义表单控件验证

[英]AngularJS custom form controls validation

我在 AngularJS 中验证自定义表单控件时遇到问题。

这两个问题是:

  1. 我想在内容可编辑字段中未修改占位符/初始文本时触发自定义错误。 我尝试了各种方法——但没有运气(包括尝试编辑$isValid )。

  2. 已解决:ng-minlengthng-maxlengthng-required无效时,我似乎无法触发错误消息上的ng-show以使其出现。 答案:我在 div 上没有名字 attr)

请参阅下面的 Plnkr 和代码示例:

https://plnkr.co/edit/Up6Q4D7cMDQQxCodLrpE?p=preview

<!doctype html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>Example - example-example40-production</title>
    <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular.min.js"></script>
    <script src="script.js"></script>
</head>

<body ng-app="form-example2">
    <form name="myForm">
        <div contentEditable="true" ng-model="standfirst" title="Click to edit" ng-required="true" ng-minlength="5" ng-maxlength="20">Some People</div>
        <p ng-show="myForm.standfirst.$error.required" class="text-danger">You did not enter a standfirst</p>
        <p ng-show="myForm.standfirst.$error.minlength" class="text-danger">Your standfirst is too short</p>
        <p ng-show="myForm.standfirst.$error.maxlength" class="text-danger">Your standfirst is too long</p>
    </form>
    <pre>model = {{content}}</pre>

    <style type="text/css">
        div[contentEditable] {
            cursor: pointer;
            background-color: #D0D0D0;
        }
    </style>
</body>

</html>
(function(angular) {
    'use strict';
    angular.module('form-example2', []).directive('contenteditable', function() {
        return {
            require: 'ngModel',
            link: function(scope, elm, attrs, ctrl) {
                // view -> model
                elm.on('blur', function() {
                    ctrl.$setViewValue(elm.html());
                });

                // model -> view
                ctrl.$render = function() {
                    elm.html(ctrl.$viewValue);
                };

                // load init value from DOM
                ctrl.$setViewValue(elm.html());
            }
        };
    });
})(window.angular);

您可以使用$pristine来检查输入值是否已更改。

<p ng-show="myForm.standfirst.$pristine" class="text-danger">Your start error message</p>

因为您在指令中在启动时设置了一个值,所以您必须重置表单。 为此,将ctrl.$setPristine()到您的代码中

// load init value from DOM
ctrl.$setViewValue(elm.html());
ctrl.$setPristine();

暂无
暂无

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

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