简体   繁体   English

创建AngularJS指令以对模糊进行验证

[英]Create AngularJS Directive to Validate on Blur

Hoping to re-create some of the functionality that's available to us in Angular 1.3.X -- the app I am creating has to work well (or at least well-enough) in IE 8. For that reason, I am (sadly) constrained to not using 1.3.X. 希望重新创建一些可在Angular 1.3.X中使用的功能-我创建的应用必须在IE 8中运行良好(或至少足够好)。因此,我(可悲)限制为不使用1.3.X。 I've been running into some trouble trying to emulate the $ng-touched attr that is available in 1.3.X. 我在尝试模仿1.3.X中可用的$ng-touched attr时遇到了一些麻烦。

One part of our app needs to alert users that their form element is invalid if they've tab -bed through it. 我们的应用程序的一部分需要提醒用户,如果他们对表单元素进行了tab浏览,则该表单元素无效。 As it stands, it doesn't set the $invalid attr on any form elements unless I've entered in text and deleted it. 就目前而言,除非我输入了文本并将其删除,否则它不会在任何表单元素上设置$invalid attr。 I tried using $pristine and $dirty to achieve $invalid after tabbing through, but they both seem to act based on the input's value, not whether it's been touched (maybe this was one of the big advantages of 1.3.X) 我尝试使用$pristine$dirty来实现$invalid invaliding,但它们似乎都是根据输入的值来执行操作,而不是根据输入的值来决定(也许这是1.3.X的一大优点)

Goal : when a user tabs through a form, validations can be fired and set each empty form element as $invalid if it's blank. 目标 :当用户通过表单进行制表时,可以触发验证,并将每个空白表单元素设置为$invalid如果为空)。 Basically to emulate the behavior of the $ng-touched attr in 1.2.X. 基本上是模拟1.2.X中$ ng接触的attr的行为。 Here's what I have so far: 这是我到目前为止的内容:

angular.module('goodStewardApp')
.directive('chf-validate', function () {
return {
  require: 'ngModel',
  link: function(scope, elm, attrs, ctrl) {
    $(elm).blur(
      function(elm) {
        ctrl.$setValidity(elm, false);
      }
    );
  }
};
});

Any help would be greatly appreciated. 任何帮助将不胜感激。 Thanks! 谢谢!

Turns out the best way to accomplish emulating the behavior of ng-touched in angular 1.2.x is to use ngBlur to set a validation attribute to be true. 事实证明,在Angular 1.2.x中模拟ng-touched行为的最佳方法是使用ngBlur将验证属性设置为true。 So: 所以:

<form name="aForm">

   <input name="foo" ng-model="foo.bar" ng-blur="validateThisElement=true" ng-required="true">

   <div ng-show="aForm.foo.$error.required && validateThisElement"> 
      Oh no! An alert!
   </div>

</form>

This allows you to run a validation after a user tab s through your form, a common way that people used to using computers will use to interact with your angular form/app. 这使您可以在用户tab浏览表单后进行验证,这是人们习惯于使用计算机的一种常见方式,用于与您的角度表单/应用程序进行交互。 Hope this helps anyone still stuck w/ 1.2.X for IE8 reasons! 希望这可以帮助任何由于IE8原因而仍然停留在w / 1.2.X下的人!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM