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

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

问题描述

例如我有我在哪里显示表单输入错误的形式。

我需要显示红色徽章(用'悬停显示错误')附近的输入标签,如果有一些错误。如果用户将鼠标悬停这个红色徽章 - 他将看到使用 AngularJS UI引导提示。
我不想把错误转化为工具提示HTML不安全的属性的列表,因为它不是方便编辑和维护。

这code是更具声明:

 <验证-NG提示秀=$ appForm.number无效和放大器;&安培; appForm.number $脏>
    < UL>
        <李NG秀=$ appForm.number error.required。>这字段是必需的< /李>
        <李NG秀=$ appForm.number error.number。>应数与LT; /李>
        <李NG秀=$ appForm.number error.min。>最低 - 5℃/李>
        <李NG秀=$ appForm.number error.max。> miximum - 20℃/李>
    < / UL>
< /验证,提示>

比这个code:

 <跨度提示-HTML不安全={{< UL><李>这字段是必须的;< /李><李> ...&LT ; /李>< / UL>}}>悬停显示错误< / SPAN>

如何编写使用AngularJS UI引导提示?这样的验证,提示指令

或者,也许你能提出其他方法来维持验证错误信息?


解决方案

演示小提琴

确认指令的工具提示

该validationTooltip是主要的指令。它具有以下职责:


  

      
  1. 通过其transcluded内容定义刀尖模板

  2.   
  3. 跟踪验证前pressions的,以便它们可以相互消化循环进行评价。

  4.   
  5. 揭露控制器API允许valiationMessage指令来注册自己

  6.   
  7. 提供有关该指令的一个'目标'属性来指定哪些表单字段徽章(以及相关的工具提示)将被绑定到

  8.   

其他注意事项

工具提示模板使用transclusion函数从链接功能到模板的指令的范围进行绑定。有两个属性是范围内的,该模板可以结合:


  

      
  1. $形式:绑定到父范围内定义的表单模型。即$ scope.myForm

  2.   
  3. $领域:绑定到父范围form.name模式。即$ scope.myForm.myInput

  4.   

这可以使模板绑定验证属性,如$有效,无效$,$质朴,$脏,$错误,而不直接引用窗体名称或输入字段的名称。例如,下面所有的前pressions的有效结合前pressions:

$表单属性:


       
  • `$形式。$ valid`

  •    
  • `$形式。$ invalid`

  •    
  • `$形式。$ dirty`

  •    
  • `$形式。$ pristine`

  •    
  • `$形式。$ error.required`等...

$字段属性:


       
  • `$域。$ valid`

  •    
  • `$域。$ invalid`

  •    
  • `$域。$ dirty`

  •    
  • `$域。$ pristine`

  •    
  • `$域。$ error.required`等...

指令实施

  app.directive('validationTooltip',函数($超时){
    返回{
        限制:'E',
        transclude:真实,
        要求:'^形式,
        范围: {},
        模板:'<跨度类=标签标签危险span1NG秀=ERRORCOUNT大于0>悬停显示ERR< / SPAN>,
        控制器:函数($范围){
            VAR前pressions = [];
            $ scope.errorCount = 0;
            这一点。$ ADDEX pression =功能(表达式){
                前pressions.push(表达式);
            }
            $范围。$表(函数(){
                变种数= 0;
                angular.forEach(如pressions,功能(表达式){
                    如果($范围。$的eval(表达式)){
                        ++计数;
                    }
                });
                返回计数;            },功能(的newval){
                $ scope.errorCount =的newval;
            });        },
        链接:功能(范围,元素,属性,表单控制器,transcludeFn){
            。范围$形式=表单控制器;            transcludeFn(范围,功能(克隆){
                VAR徽章= element.find('标签。);
                VAR提示= angular.element('< D​​IV CLASS =validationMessageTemplate工具提示危险/>');
                tooltip.append(克隆);
                element.append(提示);
                $超时(函数(){
                    。范围$字段=表单控制器[attr.target]
                    badge.tooltip({
                        位置:正确的,
                        HTML:真实,
                        标题:克隆
                    });                });
            });
        }
    }
});

验证消息指令

该validationMessage指令跟踪验证消息的工具提示中显示。它采用 NG-如果来定义前pression评估。如果没有 NG-IF 元素上找到,那么前pression简单的计算结果为真(始终显示)。

  app.directive('validationMessage',函数(){
    返回{
        限制:'A',
        优先级:1000,
        要求:'^ validationTooltip',
        链接:功能(范围,元素,属性CTRL){
            。CTRL $ ADDEX pression(attr.ngIf ||真);
        }
    }
});

在HTML中使用


  

      
  1. 添加形式与名称属性

  2.   
  3. 添加一个或多个表单域 - 每一个name属性和NG-模型指令

  4.   
  5. 声明一个<验证,提示> 目标元素属性指的是一个名称表单域。

  6.   
  7. 应用验证消息指令每个消息与一个可选的 NG-如果结合前pression

  8.   

 < D​​IV纳克级={'表单组:真实的,有错误:form.number $无效}>
    < D​​IV CLASS =行>
        < D​​IV CLASS =COL-MD-4>
            <标签=号>数字与LT; /标签>
            <验证,提示目标=号>
                < UL类=列表的无样式>
                    <李验证消息NG-IF =&GT$场error.required $;需要此领域与LT; /李>
                    <李验证消息NG-IF =$ $领域error.number。>应数与LT; /李>
                    <李验证消息NG-IF =$ $领域error.min。>最低 - 5℃/李>
                    <李验证消息NG-IF =$ $领域error.max。> miximum - 20℃/李>
                < / UL>
            < /验证,提示>
        < / DIV>
    < / DIV>
    < D​​IV CLASS =行>
        < D​​IV CLASS =COL-MD-4>
            <输入类型=数字分=5最大=20NG-模式=数字NAME =号级=表格控要求/>
        < / DIV>
    < / DIV>
< / DIV>

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:

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

$field properties:

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

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引导提示显示表单输入错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆