【问题标题】:How to create an angular validation message directive如何创建角度验证消息指令
【发布时间】:2013-08-29 11:26:41
【问题描述】:

我是 Angular 的新手,可能试图做错事。

我正在尝试创建一个验证消息指令,它可以显示表单中特定输入字段的验证消息。如果输入字段缺少值,它应该只显示必填字段的验证消息。

我尝试过使用以下 HTML:

<!DOCTYPE html>
<html ng-app="myApp">

  <head>
    <link rel="stylesheet" href="style.css">
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>
    <script src="script.js"></script>
  </head>
  <body>    
    <form name="myForm">
  <input name="myInput" type="text" x-ng-model="object.input" required/><br/> 
  <span ng-show="myForm.myInput.$error.required" >Value required (working)</span><br/>
     <span x-msg-required="myForm.myInput"></span>
    </form>
  </body>
</html>

和JS:

var app = angular.module('myApp', []);
app.directive('msgRequired', function() {
  return {
    link : function(scope, element, attrs) {
      element.text('Value required');
      attrs.$set('ngShow', attrs.msgRequired + '.$error.required' );
    }
  };

});

第一个带有 out 指令的 span 元素按预期显示验证消息。我的指令的 span 元素似乎总是显示验证消息。我肯定不理解角度的指令。我错过了什么或者有更好的方法来简化角度验证消息?

有个笨蛋:http://plnkr.co/edit/Gjvol8inw1DlWjHomZQw

【问题讨论】:

标签: angularjs angularjs-directive


【解决方案1】:

我也被 Angular 所困扰,并在 AngularAgility 中创建了一个名为 Form Extension 的指令套件来解决这个问题。它会根据您元素上的内容自动为您生成验证消息。它也是非常可配置的,如果您愿意,甚至可以为您生成标签。

考虑通常必须输入类似这样的内容才能获得验证:

<div ng-form="exampleForm">
    <label for="firstName">First Name *</label>
    <div>
        <input type="text" id="firstName" name="firstName" ng-model="person.firstName"
               ng-minlength="2" />
        <div ng-show="exampleForm.firstName.$dirty && exampleForm.firstName.$error.minlength">
            First Name must be at least 2 characters long.
        </div>
    </div>
</div>

这很痛苦。使用该插件,您可以执行以下操作:

<div ng-form="exampleForm">
    <div>
        <input type="text" aa-auto-field="person.firstName" ng-minlength="2" />
    </div>
</div>

以下是一些相关链接:

Extensive demo

Blog post explaining it

Source on GitHub

【讨论】:

    【解决方案2】:

    所以我看到这是几个月前的事了,但如果有人正在寻找有用的东西:

    我将您的 Javascript 更新为:

    var app = angular.module('myApp', []);
    
    app.directive('msgRequired', function($compile) {
        return {
          //transclude: true,
          restrict: "A",
            link: function(scope, element, attrs) {
                element[0].innerHTML = 'Value required in angular directive';
                attrs.$set('ngShow', attrs.msgRequired + ".$error.required");
    
                $compile(element)(scope)
            }
        };
      });
    

    这似乎有效。然而,我在另一个项目中做了一些非常相似的事情,并得到了一个无限的编译循环:(正在调查...

    plnkr 生活在here

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-12-26
      • 1970-01-01
      • 1970-01-01
      • 2018-03-21
      • 1970-01-01
      • 2020-08-02
      • 1970-01-01
      • 2023-03-13
      相关资源
      最近更新 更多