如何创建角度验证消息指令

时间:2013-08-29 11:26:42

标签: angularjs angularjs-directive

我是棱角分明的新手,也许是想做错事。

我想要的是创建一个验证消息指令,它可以显示表单中特定输入字段的验证消息。它应该仅在输入字段缺少值时显示必填字段的验证消息。

我尝试使用以下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元素按预期显示验证消息。带有my指令的span元素似乎总是显示验证消息。我肯定不理解角度指令。我缺少什么,或者是否有更好的方法来简化角度验证消息?

有一个plunker:http://plnkr.co/edit/Gjvol8inw1DlWjHomZQw

2 个答案:

答案 0 :(得分:4)

我也对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

答案 1 :(得分:0)

所以我看到这已经有几个月了,但万一有人在寻找有用的东西:

我将您的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