AngularJS自定义表单控件验证

时间:2016-05-05 20:46:43

标签: angularjs contenteditable angularjs-forms

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

这两个问题是:

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

  2. 已解决:我似乎无法在错误消息上触发ng-minlength,以便在ng-maxlengthng-required时显示错误消息,<!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> 无效。 (答案:我在div上没有名字attr)

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

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

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

1 个答案:

答案 0 :(得分:1)

您可以使用$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();
相关问题