如何使用 AngularJS UI Bootstrap 工具提示显示表单输入错误? [英] How to show form input errors using AngularJS UI Bootstrap tooltip?

查看:27
本文介绍了如何使用 AngularJS UI Bootstrap 工具提示显示表单输入错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,我在表单中显示表单输入错误.

如果有一些错误,我需要在输入标签附近显示红色徽章(带有悬停以显示错误").如果用户将鼠标悬停在这个红色徽章上 - 他将看到使用 AngularJS UI Bootstrap 工具提示的错误列表.我不想把错误列表放到 tooltip-html-unsafe 属性中,因为不方便编辑和维护.

此代码更具声明性:

<validation-tooltip ng-show="appForm.number.$invalid && appForm.number.$dirty"><ul><li ng-show="appForm.number.$error.required">这个字段是必填的</li><li ng-show="appForm.number.$error.number">应该是数字</li><li ng-show="appForm.number.$error.min">最小 - 5</li><li ng-show="appForm.number.$error.max">miximum - 20</li></validation-tooltip>

比这个代码:

<span tooltip-html-unsafe="{{<ul><li>此字段为必填项;</li><li>...</li></ul>}}">悬停以显示错误</span>

如何使用 AngularJS UI Bootstrap 工具提示编写这样的验证工具提示指令?

或者您能否建议另一种方法来维护验证错误消息?

解决方案

Demo Fiddle

验证工具提示指令

validationTooltip 是主要指令.它具有以下职责:

<块引用>

  1. 通过嵌入的内容定义工具提示模板
  2. 跟踪验证表达式,以便可以在每个摘要周期中对其进行评估.
  3. 公开控制器 API 以允许 valiationMessage 指令自行注册
  4. 在指令上提供'target'属性以指定徽章(和相关的工具提示)将绑定到哪个表单字段

附加说明

工具提示模板使用链接函数中的嵌入函数将模板绑定到指令的作用域.模板可以绑定到范围内的两个属性:

<块引用>

  1. $form:绑定到父作用域中定义的表单模型.即 $scope.myForm
  2. $field:绑定到父作用域中的 form.name 模型.即 $scope.myForm.myInput

这允许模板绑定到验证属性,例如 $valid、$invalid、$pristine、$dirty 和 $error,而无需直接引用表单名称或输入字段的名称.例如,以下所有表达式都是有效的绑定表达式:

$form 属性:

  • `$form.$valid`
  • `$form.$invalid`
  • `$form.$dirty`
  • `$form.$pristine`
  • `$form.$error.required` 等...

$field 属性:

  • `$field.$valid`
  • `$field.$invalid`
  • `$field.$dirty`
  • `$field.$pristine`
  • `$field.$error.required` 等...

指令实施

app.directive('validationTooltip', function ($timeout) {返回 {限制:'E',转置:真实,要求:'^形式',范围: {},模板:'<span class="label label-danger span1" ng-show="errorCount > 0">悬停以显示错误</span>',控制器:函数($scope){var 表达式 = [];$scope.errorCount = 0;this.$addExpression = 函数 (expr) {表达式.push(expr);}$scope.$watch(function () {无功计数 = 0;angular.forEach(表达式,函数(expr){如果($scope.$eval(expr)){++计数;}});返回计数;}, 函数 (newVal) {$scope.errorCount = newVal;});},链接:函数(范围、元素、属性、formController、transcludeFn){scope.$form = formController;transcludeFn(范围,功能(克隆){var 徽章 = element.find('.label');var tooltip = angular.element('<div class="validationMessageTemplate tooltip-danger"/>');tooltip.append(clone);element.append(工具提示);$超时(函数(){scope.$field = formController[attr.target];徽章.工具提示({位置:'正确',html:对,书名:克隆});});});}}});

验证消息指令

validationMessage 指令会跟踪要显示在工具提示中的验证消息.它使用 ng-if 来定义要计算的表达式.如果在元素上找不到 ng-if,则表达式的计算结果为 true(始终显示).

app.directive('validationMessage', function () {返回 {限制:'A',优先级:1000,要求:'^validationTooltip',链接:函数(范围、元素、属性、ctrl){ctrl.$addExpression(attr.ngIf || true );}}});

在 HTML 中的使用

<块引用>

  1. 添加具有名称属性的表单
  2. 添加一个或多个表单字段 - 每个字段都有一个 name 属性和一个 ng-model 指令.
  3. 声明一个 元素,其中 target 属性指的是其中一个表单字段的名称.
  4. 使用可选的 ng-if 绑定表达式将 validation-message 指令应用于每条消息.

<div class="row"><div class="col-md-4"><label for="number">Number</label><validation-tooltip target="number"><ul class="list-unstyled"><li validation-message ng-if="$field.$error.required">这个字段是必填的</li><li validation-message ng-if="$field.$error.number">应该是数字</li><li 验证消息 ng-if="$field.$error.min">最小 - 5</li><li 验证消息 ng-if="$field.$error.max">miximum - 20</li></validation-tooltip>

<div class="row"><div class="col-md-4"><input type="number" min="5" max="20" ng-model="number" name="number" class="form-control" required/>

For example I have the form where I am showing form input errors.

I need to show red badge (with 'hover to show errors') near input label if there are some errors. If user will hover this red badge - he will see list of errors using AngularJS UI Bootstrap tooltip. I don't want to put list of errors into tooltip-html-unsafe attribute, because it is not convenient to edit and maintain.

This code is more declarative:

<validation-tooltip ng-show="appForm.number.$invalid && appForm.number.$dirty">
    <ul>
        <li ng-show="appForm.number.$error.required">this field is required</li>
        <li ng-show="appForm.number.$error.number">should be number</li>
        <li ng-show="appForm.number.$error.min">minimum - 5</li>
        <li ng-show="appForm.number.$error.max">miximum - 20</li>
    </ul>
</validation-tooltip>

than this code:

<span tooltip-html-unsafe="{{<ul><li>This field is required;</li><li>...</li></ul>}}">hover to show errors</span>

How can I write such validation-tooltip directive using AngularJS UI Bootstrap tooltip?

Or maybe can you suggest another approach to maintain validation error messages?

解决方案

Demo Fiddle

Validation Tooltip Directive

The validationTooltip is the main directive. It has the following responsibilities:

  1. Define the tool tip template through its transcluded contents
  2. Keep track of validation expressions so that they can be evaluated with each digest cycle.
  3. Expose a controller API for allowing valiationMessage directives to register themselves
  4. Provide a 'target' attribute on the directive to specify which form field the badge (and the associated tooltip) will be bound to

Additional Notes

The tooltip template uses the transclusion function from the link function to bind the template to the directive's scope. There are two properties that are within scope that the template can bind to:

  1. $form: Bound to the form model defined in parent scope. i.e. $scope.myForm
  2. $field: Bound to the form.name model in parent scope. i.e. $scope.myForm.myInput

This allows the template to bind to validation properties such as $valid, $invalid, $pristine, $dirty, and $error without referring to the form name or the input field's name directly. For example, all of the following expressions are valid binding expressions:

$form properties:

$field properties:

Directive Implementation

app.directive('validationTooltip', function ($timeout) {
    return {
        restrict: 'E',
        transclude: true,
        require: '^form',
        scope: {},
        template: '<span class="label label-danger span1" ng-show="errorCount > 0">hover to show err</span>',
        controller: function ($scope) {
            var expressions = [];
            $scope.errorCount = 0;
            this.$addExpression = function (expr) {
                expressions.push(expr);
            }
            $scope.$watch(function () {
                var count = 0;
                angular.forEach(expressions, function (expr) {
                    if ($scope.$eval(expr)) {
                        ++count;
                    }
                });
                return count;

            }, function (newVal) {
                $scope.errorCount = newVal;
            });

        },
        link: function (scope, element, attr, formController, transcludeFn) {
            scope.$form = formController;

            transcludeFn(scope, function (clone) {
                var badge = element.find('.label');
                var tooltip = angular.element('<div class="validationMessageTemplate tooltip-danger" />');
                tooltip.append(clone);
                element.append(tooltip);
                $timeout(function () {
                    scope.$field = formController[attr.target];
                    badge.tooltip({
                        placement: 'right',
                        html: true,
                        title: clone
                    });

                });
            });
        }
    }
});

Validation Message Directive

The validationMessage directive keeps track of the validation messages to display in the tooltip. It uses ng-if to define the expression to evaluate. If there is no ng-if found on the element, then the expression simply evaluates to true (always shown).

app.directive('validationMessage', function () {
    return {
        restrict: 'A',
        priority: 1000,
        require: '^validationTooltip',
        link: function (scope, element, attr, ctrl) {
            ctrl.$addExpression(attr.ngIf || true );
        }
    }
});

Usage in HTML

  1. Add a form with a name attribute
  2. Add one or more form fields - each with a name attribute and an ng-model directive.
  3. Declare a <validation-tooltip> element with a target attribute referring to the name of one of the form fields.
  4. Apply the validation-message directive to each message with an optional ng-if binding expression.

<div ng-class="{'form-group': true, 'has-error':form.number.$invalid}">
    <div class="row">
        <div class="col-md-4">
            <label for="number">Number</label>
            <validation-tooltip target="number">
                <ul class="list-unstyled">
                    <li validation-message ng-if="$field.$error.required">this field is required </li>
                    <li validation-message ng-if="$field.$error.number">should be number</li>
                    <li validation-message ng-if="$field.$error.min">minimum - 5</li>
                    <li validation-message ng-if="$field.$error.max">miximum - 20</li>
                </ul>
            </validation-tooltip>
        </div>
    </div>
    <div class="row">
        <div class="col-md-4">
            <input type="number" min="5" max="20" ng-model="number" name="number" class="form-control" required />
        </div>
    </div>
</div>

这篇关于如何使用 AngularJS UI Bootstrap 工具提示显示表单输入错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
其他开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆